简体   繁体   中英

Node.JS - MySQL Module is not Recognized

I am having this issue since more than one month and I read all related posts on stackoverflow and other sites but none of them worked out with me! The MySQL module of Node.js is not getting recognized by Node.js

I have installed Node.js as below:

apt-get install nodejs

Then installed the npm as below:

apt-get install npm

Then installed the MySQL module as below:

npm install -g mysql

I also tried the below without any success too!

npm install mysql

When I run the Node.js server like below:

node /var/www/server.js

I get:

node.js:201
    throw e; // process.nextTick error, or 'error' event on first tick
          ^
Error: Cannot find module 'mysql'
    at Function._resolveFilename (module.js:332:11)
    at Function._load (module.js:279:25)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at Object.<anonymous> (/var/www/server.js:2:13)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:32)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)

The content of server.js as below

console.log("Hello World");
var mysql = require('mysql');

Update: When I used

cd /var/www/

then

npm install mysql

The MySQL doesn't work, I use the below to connect to MySQL

var db_config = {
    host      : 'localhost',
    user      : 'xxx',
    password  : 'xxx',
    database  : 'xxx'
};

var connection;

function handleDisconnect(){

    connection = mysql.createConnection(db_config);


    connection.connect(function(err) {
        if(err) {
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 2000);
        }
    });

    connection.on('error', function(err) {
        console.log('db error', err);
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        }
        else{
             throw err;
        }
    });
 }

 handleDisconnect();   

I am not into advance settings of Node.js and I like to work on simple commands.

I would greatly appreciate your advise because I face this issue whenever I install Node.js on the server. Thanks.

Try the following:

cd /var/www/
npm install mysql

This way the mysql module will be installed locally on your node directory.

My guess is that you have tried to install the module from another directory, not from where your server.js located.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM