我有一个 Express.js Web 应用程序。在主 app.js
文件中,我 require()
一堆第三方依赖项。最近,我开始将部分 app.js
代码提取到单独的模块中,例如
// in app.js
var users = require('./modules/users');
// and then e.g.
// users.add(doc);
在我的模块中,我有时需要使用主 app.js
文件中可用的对象,我想知道将对这些对象的引用传递给我的模块的最佳方法是什么。
我目前的方法:
// in app.js
// pass needed object references in initialization step
users.init([db, logger]);
和
// in modules/users.js
var db, logger;
exports.init = function (deps) {
db = deps[0];
logger = deps[1];
};
这种方法有意义吗?有更好的方法来执行此操作吗?
最佳答案
当然,只需使用模块即可! :)
// db.js
// create db instance here rather than in app.js
module.exports = db;
还有
// logger.js
// create logger instance here rather than in app.js
module.exports = logger;
然后
// app.js
var db = require('./db');
还有
// lib/somewhere.js
var db = require('../db');
这样,您就可以依赖 CommonJS 依赖注入(inject)系统,而不是自己进行依赖注入(inject)(传递引用,而不是需要
将模块插入到您的模块中)。
其按预期工作的原因是模块仅被解释一次,因此如果您将所有内容实例化一次而不是使用工厂函数,它就会工作。
关于javascript - 如何使对象引用在 Node 模块中可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549731/