module.require(...).*是否返回module.exports.*的副本或它的引用? [英] Does module.require(...).* return a copy of module.exports.* or a reference of it?

查看:183
本文介绍了module.require(...).*是否返回module.exports.*的副本或它的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,session.js和user.js中的"db"变量是指向db.js中的同一对象还是它们的副本(建立与我的db服务器的单独连接)?

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;
......

谢谢!

推荐答案

每次调用require('../db.js')都会返回相同的对象,因此在您的情况下,只会创建一个database连接池.

Every call to require('../db.js') returns the same object, so in your case there would just be a single database connection pool created.

请注意,database实际上是一个连接池(默认情况下为5个),可以在您的代码之间自由共享,因此这很可能是您想要的.

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.

请参见文档此处.

这篇关于module.require(...).*是否返回module.exports.*的副本或它的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆