Reputation: 7864
//module.js
exports.doA = function(callback) {
db.asyncConnect(/* connect options */, function(err, database) {
if(err == null) {
exports.db = database;
}
});
}
exports.db = null;
// test1.js
var mydb = require('module');
console.log(mydb);
// test2.js
var db = require('module').db;
console.log(db);
How is var mydb = require('module');
different from var mydb = require('module').db;
?
Update: Updating with the code and behavior I am observing
// file: db.js
exports.init = function (start_server){
MongoClient.connect(url, {
db: {
raw: true
},
server: {
poolSize: 5
}
},
function(err, database) {
exports.db = database;
if(err == null)
start_server();
}
);
}
exports.db = null;
.
// file: test.js
var mongodb = require('./db.js');
var db = require('./db.js').db;
console.log("MongoDb " + mongodb.db);
console.log("DB " + db);
Output: MongoDb [object Object] DB null
Q. The variable db
is coming out to be null but mongodb.db
is having values?
Even if I assign the value of mongodb.db
in a variable, the value is coming out to be null.
Upvotes: 0
Views: 73
Reputation: 47202
var mydb = require('module');
This gets the entire module.
var mydb = require('module').db;
This gets the property db
of the object that the module returns.
The downside to the latter part is that you can't access the "parent" object anymore, ie. whatever is returned from the .db
call, will be what you get and nothing else.
Quick example:
//some_module.js
var SomeModule = {
db: function () {
console.log("hello");
}
};
module.exports = SomeModule;
//some_other_module.js
var SomeModule = require('./some_module.js');
console.log(SomeModule); // [Object object]
var SomeDB = require('./some_module.js').db;
console.log(SomeDB); // function () {}
Upvotes: 2
Reputation: 2051
It's basically different
var mydb = require('module');
That means every object
that you export will be called/ imported. mydb.doA
and mydb.db
are available.
var db = require('module').db;
Only db
object is called/ imported to your code. Different from first example, db
it self is like mydb.db
in the first example.
Upvotes: 0