Simer Simer - 4 years ago 101
Node.js Question

how to use variable of one module in other in express node js

I have one file where I have written following code:

var db_abc= express();
var mysql = require('mysql')

var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'abc_db'
})

connection.connect(function (err) {
if (err) throw err
console.log('You are now connected...')

})

module.exports = db_abc;


Now I want to use connection in other file to write queries:

var db_abc = require('../db_abc')

db_abc.connection.query('SELECT tid, type, status, ' +
'created, modified, jdp_response FROM jdp_tb_trade ' +
'WHERE status="TRADE_FINISHED" AND type = "tmall_i18n" ' +
//'AND DATE_ADD(NOW(), INTERVAL ' + start + ' MINUTES) <= modified' +
// 'AND DATE_ADD(NOW(), INTERVAL ' + end + ' MINUTES) >= modified' +
'ORDER BY modified',
function (err, results) {
if (!err)
console.log('The solution is: ', results);
else
console.log('Error while performing Query.');

});


If I write above query in same file where I have define connection then it successfully executes. but when I use db_abc module and import it and use connection variable to call query then it says query is not define.

Any suggestion on how to use variables of other module in express would be appreciated.

Answer Source

You are exporting db_abc which is an express application. Express does not have a connection variable.

I think that you wanted to do something like

var db_abc= express();
var mysql = require('mysql')

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'abc_db'
})

connection.connect(function (err) {
  if (err) throw err
  console.log('You are now connected...')
})

module.exports = {
  connection, // Export connection here
};

And then you can use it like this

var db_abc = require('../db_abc')
db_abc.connection...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download