15

抱歉,如果这是一个愚蠢的问题,但是如果我创建了 2 个模块,它们都需要('http')和需要这两个模块的主应用程序,或者需要反过来需要两个模块的模块,同时也需要自己的“http”目的,我是否最终得到了 http 模块的三个实例,每个实例都锁定在不同的闭包范围内,还是节点重写了一些东西以避免这种情况?

换句话说,我最终得到的应用程序是否具有:

// main app  creates a closure containing a local instance of http, an instance of proxy1
// and an instance of proxy2, both of which are functions returned from closures that have instances of http in scope
var http = require('http'),
    httpProxy1 = require('./proxy1'),
    httpProxy2 = require('./proxy2');

/* ... do stuff with http, using proxy1 or proxy2 where appropriate ... */


// proxy1 creates a closure containing a local instance of http and exposes a single public method
var http = require('http');
module.exports = function (foo) { /* ... do stuff with http ... */ }

// proxy2  creates a closure containing a local instance of http and exposes a single public method
var http = require('http');
module.exports = function (foo) { /* ... do stuff with http that has nothing to do with the stuff proxy1 does ... */ }

如果我也想独立使用proxy1,将它作为一个模块是有意义的,但即使是在一个小项目上,这也可能导致许多模块都重复需要核心模块,尤其是http和fs

4

1 回答 1

14

阅读 Node.js 的模块加载如何缓存模块。在您的示例中,所有模块中的“http”实例都是相同的。

但请注意,模块是根据解析的文件名缓存的。当需要像“http”这样的内置模块时,您可以合理地确定您在所有代码中都获得了相同的模块对象。但是第 3 方包不一定会以这种方式运行。例如,如果你需要'express'和'mime',我相信你得到的'mime'模块对象将与express内部使用的不同。原因是 express 在其 node_modules 子目录中附带了它自己的一组模块文件,而您将安装并加载自己的副本,可能在您的 your_project/node_modules 某处

于 2011-10-02T05:28:29.050 回答