node.js - nodejs模块和重复?如果一个应用程序使用了两个需要一个公共(public)模块的模块, Node 是否会优化以防止两次加载相同的代码?

标签 node.js module duplication

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

最佳答案

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

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

关于node.js - nodejs模块和重复?如果一个应用程序使用了两个需要一个公共(public)模块的模块, Node 是否会优化以防止两次加载相同的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7622385/

相关文章:

javascript - 如何将对象中的每个值写入文本文件中的每一行

python - Docker 上的 Odoo 开发

未找到 Haskell 模块。我的项目的文件结构有什么问题?

postgresql - 避免在 PostgreSQL 中的 SELECT 查询中重复值

c++ - 如何复制当前进程?

node.js - 机器人对话框未启动

node.js - Mongodb更新数组中现有项目的新位置,如果不存在则添加新位置

node.js - Sequelize 急切加载 : hasMany include parent

javascript - 如何共享作为对象属性的函数并避免重复代码

PostgreSQL:在同一台服务器上即时复制数据库