5

A new instance of third-party module should be required in one of the modules.

// a
...
exports.thirdParty = require('third-party');

// b
...
exports.thirdParty = require('third-party');

// first-party
...
exports.thirdParty = requireFreshInstance('third-party');

// app.js
var assert = require('assert');
var a = require('a');
var firstParty = require('first-party');
var b = require('b');

assert(a.thirdParty === b.thirdParty);
assert(firstParty.thirdParty !== a.thirdParty);
assert(firstParty.thirdParty !== b.thirdParty);

All of the listed modules have similar package requirements,

dependencies: {
  "third-party": "^1"
}

And the requirement is that it should stay intact, no tricks like "third-party": "git://..." are allowed.

Let's say the user controls only first-party module and can't modify third-party module to have a new factory method that would return a new instance.

I'm aware of the fact that third-party is cached once if the version is the same in all cases (technically it is full path to third-party that matters), most likely .thirdParty properties in all objects are equal.

How can this problem be solved in Node.js programmatically (not with package.json)?

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • maybe related to this http://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate. Try using `delete require.cache['third-party']`. – peacer212 Feb 25 '16 at 01:37
  • Maybe this module `https://github.com/gajus/require-new` could solve your issue? – zangw Feb 25 '16 at 03:06
  • @zangw Great, thanks, looks like exactly what I need. Feel free to post it as an answer if you wish. – Estus Flask Feb 25 '16 at 03:30
  • @peacer212 Yes, it is related but the problem is more complex. deleting module cache will affect all modules that require 'third-party'. – Estus Flask Feb 25 '16 at 03:31

1 Answers1

2

Here is one module require-new could meet your requirement.

  • require-new requires a new module object.

  • require-new does not affect the state or behavior of require method.

  • require-new has been designed to be used for module testing.

Here are sample from this module.

require('./rand.js'); // 0.697190385311842
require('./rand.js'); // 0.697190385311842

Modules are cached in a require.cache object when they are required.

require-new deletes the key value from the require.cache object associated with the module you are requesting, making the module reload:

requireNew('./rand.js'); // 0.2123227424453944
requireNew('./rand.js'); // 0.5403654584661126
zangw
  • 43,869
  • 19
  • 177
  • 214
  • It won't resolve to a different copy if module path is the same (and it is the same). For loose version restriction (like in my case) only one copy of third-party will be installed, `node_modules/third-party` with npm2, `node_modules/third-party@1.0.0` with npm3. There won't be `node_modules/a/node_modules/third-party`. – Estus Flask Feb 25 '16 at 02:34