I'm curious about the way NodeJS exports it's modules. I know to export a method, we write the exports keyword.methodname.
However, my module is a connection:
//Require mysql connector that you installed with npm
var mysql = require('mysql');
var conn_conf = {
host : 'localhost',
port : 3306,
user : 'root',
password : 'root',
database : 'nutrition_tracker'
}
var connection = mysql.createConnection(conn_conf);
connection.connect(function(err) {
if(err) console.log("Could not connect to DB");
else{
console.log("Connected to "+conn_conf.database+' on '+conn_conf.host );
}
});
Then in the file that requires it:
var db2 = require('../db/mysql_conn');
console.log(db2)
But everytime, db2 is {}. I can't understand why - shouldn't me requiring the module give me the connection? I even tried returning the connection within the module, but the same thing - db2 was {}.
Add this line at the end of your module file:
exports = module.exports = connection;
Note that your approach is flawed as you don't know what is the status of the connection returned by your require() call. You might send a query before the connection was opened.
A better approach would be to export a factory function instead:
exports = module.exports = function(cb) {
// your code as above
// ...
connection.connect(function(err) {
if(err) {
console.log("Could not connect to DB");
cb(err);
} else {
console.log("Connected to "+conn_conf.database+' on '+conn_conf.host );
cb(null, connection);
}
});
};
And use it this way:
var createDb = require('../db/mysql_conn');
createDb(function(err, db2) {
console.log(db2);
});
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.