简体   繁体   中英

Node.js: how to load modules without executing them?

I have a simple file model.js like follows:

var mongo = require('mongodb');

var mongoUri = process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    'mongodb://localhost/mydb';

exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
    console.log("Connect to the database successfully")
});

and in my web.js I load the model using model = require('./model.js') . One werid thing is that although I did not call model.connect() , the message "Connect to the database successfully" still got logged to my console. Why is this happening and is there a way to avoid it?

EDIT :Never mind I have found a workaround:

exports.connect = function(){
     mongo.Db.connect(mongoUri, function(err, db) {
        console.log("Connect to the database successfully")
     });
}
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
    console.log("Connect to the database successfully")
});

You just called mongo.Db.connect() and assigned its result to exports.connect .
That code runs as soon as you require() the module.

Instead, you need to create a function:

exports.connect = function() { ... };

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