与其直接导出模块的内容,您可以将其包装在一个函数中,然后每次需要该内容时调用该函数。我使用这种模式进行模块可能需要的任何类型的初始化。这里有一个简单的(傻)例如:
// this module will always add 1 to n
module.exports = function(n) {
return 1 + n;
}
VS:
module.exports = function(n1) {
// now we wrapped the module and can set the number
return function(n2) {
return n1 + n2;
}
};
var myModule = require('that-module')(5);
myModule(3); // 8
而另一个例子,它包含不断变化的数据:
// ./foo
module.exports = {
foo: Date.now()
};
// ./bar
module.exports = function() {
return {
foo: Date.now()
};
};
// index.js
var foo = require('./foo');
var bar = require('./bar');
setInterval(function() {
console.log(foo.foo, bar().foo);
}, 500);
来源
2015-04-06 03:25:31
m59
才有模块返回,返回的东西的功能你想刷新,然后在需要时调用该函数。合理? – m59 2015-04-06 01:49:16
呃这么认为,我会试一试喊我,如果你找到一个例子。 Thx – saj 2015-04-06 01:53:20
http://runnable.com/VSHpLtbzq6dQTCw7/sdfsdf-for-node-js-and-hello-world – m59 2015-04-06 02:03:49