首先导出函数,然后导出对象

时间:2013-08-28 12:47:54

标签: javascript node.js node-modules

我有一个自定义模块,并希望提供一种方法来在require初始化它,但是在后续需求中直接返回一个对象。

但是模块在首次需要时会被缓存,因此后续需要仍然返回init函数,而不是直接返回obj

server.js:

var module = require('./module.js');
var obj = module.init();
console.log('--DEBUG: server.js:', obj); // <-- Works: returns `obj`.

require('./other.js');

other.js:

var obj = require('./module.js');
console.log('--DEBUG: other.js:', obj); // <-- Problem: still returns `init` function.

module.js:

var obj = null;

var init = function() {
    obj = { 'foo': 'bar' };
    return obj;
};

module.exports = (obj) ? obj : { init: init };

我该如何解决这个问题?或者是否有实现这种目标的既定模式?

但我希望保持obj缓存,因为我的真实init做了一些工作,我宁愿不在每个require上做。

1 个答案:

答案 0 :(得分:2)

有一些方法可以清除require缓存。你可以在这里查看node.js require() cache - possible to invalidate? 但是,我认为这不是一个好主意。我建议你传递你需要的模块。即只初始化一次并将其分发给其他模块。

server.js:

var module = require('./module.js');
var obj = module.init();

require('./other.js')(obj);

other.js:

module.exports = function(obj) {
    console.log('--DEBUG: other.js:', obj); // <-- The same obj
}

module.js:

var obj = null;

var init = function() {
    obj = { 'foo': 'bar' };
    return obj;
};

module.exports = { init: init };