2013-08-28 50 views
0

我有一個自定義模塊,並希望提供一種初始化它的方法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 }; 

我怎麼能窩k圍繞這個問題?還是有一個既定的模式實現這樣的?

但我想保留obj緩存,因爲我的真實init做了一些工作,我寧願不要在每個require上做。

回答

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 }; 
相關問題