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

道歉,如果这是一个愚蠢的问题,但如果我创build两个模块都需要('http')和我的主要应用程序需要这两个模块,或需要模块,而这又需要两个模块,同时也需要“http”目的,我最终有三个实例的http模块,每个locking在不同的闭包范围内,或者节点重写的东西,以避免这种情况?

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

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

阅读Node.js模块如何加载caching模块 。 在你的例子中,所有模块中的“http”实例将是相同的。

但请注意,模块是基于parsing的文件名进行caching的。 当需要像“http”这样的内置模块时,你可以合理地确定你在所有的代码中获得了相同的模块对象。 但是第三方软件包并不一定这样。 例如,如果你需要“express”和“mime”,我相信你所得到的“mime”模块对象将与express里面使用的不同。 原因是,在它的node_modules子目录中,expression自己的一套模块文件,而您将已经安装并加载自己的副本,可能在您的your_project / node_modules某处