nodejs modules and duplication? If an app uses two

2020-08-10 07:52发布

问题:

Apologies if this is a dumb question, but if I create 2 modules that both require('http') and my main application that requires both modules, or requires modules that in turn require both modules, while also requiring 'http' for its own purposes, do I end up with three instances of the http module, each locked within the scope of a different closure, or does node rewrite things to avoid this?

In other words, do I end up with an app that has:

// 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 ... */ }

If I also want to use proxy1 independently, it makes sense to have it as a module, but on even a small project, this could lead to many modules that all require core modules repeatedly, especially http and fs

回答1:

Read up on how Node.js' module loading caches modules. In your example, the 'http' instance will be the same across all your modules.

But be aware that modules are cached based on resolved filename. When requiring a built-in module like 'http' you can be reasonably sure you're getting the same module object across all your code. But 3rd party packages don't necessarily behave this way. For example, if you require 'express' and 'mime', the 'mime' module object you get will, I believe, be different from the one that's used inside of express. The reason being that express ships with it's own set of module files in it's node_modules subdirectory, while you will have installed and loaded your own copy, probably in your your_project/node_modules somewhere