Vikas Kumar Vikas Kumar - 28 days ago 15
Node.js Question

Why is it showing connection not defined?

I'm trying to use

connection
from a connection.js file and use it in different file webFrontend.js using
exports
object. Now what I get on running server is:

{
"Result": "undefinedThis is result"
}


That means
connection
is not defined. Why is it happening?
connection
is working fine if
getConnection
is created in same (webFrontend.js) file, but the problem is when I use
getConnection
in same exports function in connection.js hence the
connection
not defined error:

Here are 2 necessary files (routes file has no problem) that explains what I'm doing:

connection.js

var mysql = require('mysql');
exports.connExport = function () {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
if(connectionPool) {
connectionPool.getConnection(function (err, connection) {
if (err) {
return err;
} else {
return connection;
}
});
}else{
var abc="return error";
return abc;
}
}


webFrontend.js

var connObj=require('../Routes/connection.js');
var connection=connObj.connExport();
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
return next();
};

Answer

No need for the .js file extension, it's automagically added for you.

The code below uses standard error-first callbacks

webFrontend.js

var connection = require('../Routes/connection');
exports.getIndivRecords = function(req, res, next){

  // connection takes a standard error-first callback
  connection(function(err, conn){
    if (err) {
      // Handle the error returned
      console.log(err);
    }
    // The database connection is available here as conn
    console.log( "Connection:" + conn);

    // presumably you want to do something here
    // before sending the response

    res.send({
      Result: conn + "This is result"
    });
  });
  return next();
};

connection.js

var mySQL = require('mysql');
var connectionPool = mySQL.createPool({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'rockcity_followme'
});
var getConnection = function (cb) {
  connectionPool.getConnection(function (err, connection) {
    // pass the error to the callback
    if (err) {
      return cb(err);
    }
    cb(null, connection);
  });
};
module.exports = getConnection;