【问题标题】:Export function first and object subsequently先导出函数,再导出对象
【发布时间】:2013-08-28 20:59:27
【问题描述】:

我有一个自定义模块,想提供一种方法来在第一个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');

其他.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 上做的工作。

【问题讨论】:

    标签: javascript node.js node-modules


    【解决方案1】:

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

    server.js:

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

    其他.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 };
    

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 1970-01-01
      • 2017-05-08
      • 2016-12-26
      • 2018-05-29
      • 1970-01-01
      • 2023-03-13
      • 2020-06-20
      • 2017-12-12
      相关资源
      最近更新 更多