skip to Main Content

I didn’t expect that I’ll stuck with this simple (at first glance) question, but I really haven’t find anything helpful about the problem. I use the following code in my connect.js file:

`let mysql = require('mysql');

let connection = mysql.createConnection({
    host: 'localhost',
    user: 'xxxxx',
    password: 'xxxxxxxxxxxxxxx',
    database: 'xxxxx'
});

connection.connect(function(err) {
    if (err) {
      return console.error('error: ' + err.message);
    }

    console.log('Connected to the MySQL server.');
});

`
then I run the following command, and recieve this response:

` $ node connect.js
file:///home/timothy/Desktop/Backend/connect.js:1
let mysql = require(‘mysql’);
^

ReferenceError: require is not defined
    at file:///home/timothy/Desktop/Backend/connect.js:1:13
    at ModuleJob.run (internal/modules/esm/module_job.js:145:37)
    at async Loader.import (internal/modules/esm/loader.js:182:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)`

I tried to remove ‘type’: ‘module’ from my package.json file, then it works as intended, I recieve console.error (but that is not the point, it’s related to my database). But if I remove ‘type’: ‘module’ my main file index.js doesn’t work, because it uses express js dependency. So now I wondering how to make both files work properly. I tried to install requirejs via

`$ npm i requirejs

`
but it doesn’t solve my problem

UPDATE:
mysql npm package is installed of course

and I see the same problem here:
How can I get all the filesnames from a directory on the server in javascript?

Many people says that this error happens when you try running code in a browser and not in a nodejs server. I don’t know if I have to specify that this file is for node server. I just run

node filename.js

As you can see, may be I miss something?

2

Answers


  1. I think your mysql npm package is not installed or an unwanted character put before
    let mysql = require('mysql'); line, so at first run npm i mysql command on your project directory. then use the following code…

    let mysql = require('mysql');
    
    let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'ecomm'
    });
    
    connection.connect(function(err) {
      if (err) {
      return console.error('error: ' + err.message);
     }
    
    console.log('Connected to the MySQL server.');
    });
    
    Login or Signup to reply.
  2. Can you try to change to this

    import * as mysql from 'mysql'
    

    or

    import mysql from 'mysql'
    

    And set type to module

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search