问题
In the following code, are the "db" variables in session.js and user.js referencing to the same object in db.js, or are they copies of it (making separate connections to my db server)?
// db.js
var mongojs = require('mongojs');
var db = mongojs('test', ['users', 'sessions']);
module.exports.database = db;
// session.js
var db = require('../db.js').database;
......
// user.js
var db = require('../db.js').database;
......
Thanks!
回答1:
Every call to require('../db.js')
returns the same object, so in your case there would just be a single database
connection pool created.
Note that database
is actually a pool of connections (5 by default) that can be freely shared across your code so this is likely what you want.
See the docs here.
回答2:
A required module is cached, so they will both point to the same object. Relevant Node.js documentation: Modules caching docs.
来源:https://stackoverflow.com/questions/13346046/does-module-require-return-a-copy-of-module-exports-or-a-reference-of-i