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

2024-01-06

如果这是一个愚蠢的问题,我深表歉意,但是如果我创建两个模块,它们都需要('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


了解 Node.js 的模块加载方式缓存模块 http://nodejs.org/docs/v0.4.12/api/modules.html#caching。在您的示例中,“http”实例在所有模块中都是相同的。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐