Does module.require(…).* return a copy of module.exports.* or a reference of it?

梦想的初衷 提交于 2019-12-11 02:05:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!