nodejs模块和重复?如果应用程序使用两个需要公共模块的模块,节点是否会优化以防止加载相同的代码两次?

use*_*611 13 module duplication node.js

如果这是一个愚蠢的问题,我会道歉,但是如果我创建两个需要('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 ... */ }
Run Code Online (Sandbox Code Playgroud)

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

bro*_*ofa 13

阅读Node.js模块加载缓存模块的方法.在您的示例中,'http'实例在所有模块中都是相同的.

但请注意,模块是基于已解析的文件名进行缓存的.当需要像'http'这样的内置模块时,您可以合理地确定在所有代码中获得相同的模块对象.但第三方包不一定表现得这样.例如,如果你需要'express'和'mime',我相信你获得的'mime'模块对象将与express中使用的那个不同.原因是快递在它的node_modules子目录中附带了它自己的一组模块文件,而你可能已经安装并加载了你自己的副本,可能在你的your_project/node_modules中