Node.js 模块和复制?如果一个应用程序使用两个需要共同模块的模块,Node.js 是否会优化以防止重复加载相同的代码?

15

如果我创建了两个模块,它们都需要 'http' 模块,而我的主应用程序需要这两个模块,或者需要进一步需要这两个模块的模块,同时还需要 'http' 模块来实现自己的目的,那么我最终会有三个 http 模块实例吗?它们是否被锁定在不同的闭包作用域内,或者 node 会重写以避免这种情况?

换句话说,我最终会得到一个具有:

// 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。

1个回答

14

阅读Node.js的模块加载中缓存模块。在你的示例中,'http'实例将在所有模块中都相同。

但要注意,模块是基于解析后的文件名进行缓存的。当需要一个内置模块像'HTTP'时,您可以合理地确定您正在获取跨所有代码相同的模块对象。但第三方软件包不一定会以此方式运行。例如,如果您需要'express'和'mime',我认为您获得的'mime'模块对象将与在express内部使用的模块对象不同。原因是express附带了其自己的模块文件集,在其node_modules子目录中,而您将安装和加载自己的副本,可能在您的your_project/node_modules中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接