Reputation: 6709
First of all I'm not so experienced in Node.js. My understanding of Node.js' modules was that those act pretty the same like Python's modules. I mean executing code only once and maintaining internal state. Until I've read this article:
But you might not realize (I sure didn't!) that if your project is based on npm modules that both require the "shared" module as a dependency, like this:
node_modules/one/index.js: var shared = require('shared'); node_modules/two/index.js: var shared = require('shared');
... And you install their dependencies with npm, there will be two copies of "shared/index.js" hanging about:
node_modules/one/node_modules/shared/index.js node_modules/two/node_modules/shared/index.js
After reading it I'm not sure, that one can rely upon module's internal state because of the possibility of the existence of one module on different paths and hence having two or more instances of the same module in the cache. This means at least "No more singletons through native modules mechanism". Meanwhile, I haven't heard about such problem in Python.
Does it mean that almost all modules have to return only functions/constructors (like express.js
app creation flow) and avoid internal state?
Upvotes: 0
Views: 513
Reputation: 22728
Internal state on node modules differs only when those modules are loaded from different paths, so it sort of depends on which version of NPM you're using and how dependencies are managed.
This really is more of an NPM question since you're likely using that to manage your dependencies.
NPM 2 has a more nested approach to installing dependencies which means you'll like have a lot more copies of a single module than you would if you install using NPM 3.
Example. Lets say you install Module A and Module B which both depend on version 1.4 of Module C, with NPM 2 you get:
+- Module A
| |
| + Module C v 1.4
|
+- Module B
|
+ Module C v 1.4
Which means Modules A and B will have entirely different versions of Module C loaded.
If you run npm dedupe
, it should idealize this tree to be:
+- Module A
|
+- Module C v 1.4
|
+- Module B
This flatter tree is also what NPM 3 attempts to create.
Having worked on systems where we were trying to rely on the inherent single-instance of a shared module being present, I would recommend trying to NOT do that. NPM 2 dedupe
has its fair share of issues, and NPM 3 still has some performance issues with it.
Upvotes: 1