1

Does anyone know how to use node's native "module" module (!) to load in a module manually from file as an alternative to using the normal require mechanism?

I know it's an odd request, but I need modules that declare their variables globally (to that module) and that are wrapped as new modules each time they are required, e.g.

var private;

module.exports = {
    setPrivate: function (value) {private = value} 
}

To elaborate, if you call require twice in separate places with the same path you get the same module back. I need to always get a new module so that when required in twice setPrivate can only affect its own variable;

Basically, I need to work out the mechanism that require() uses to create and return a module the first time it is called. Have played around with instantiating Module directly (as in https://github.com/joyent/node/blob/master/lib/module.js#L293), but no luck - the exports property is always an empty object.

Please guys no suggestions to just use a constructor... I appreciate I have an unusual use case.

1 Answer 1

1

You don't need to do anything so complicated.

Instead, you can simply delete it from the cache:

delete require.cache[module.id];
Sign up to request clarification or add additional context in comments.

6 Comments

This is reasonable, though not ideal. It would be preferable to cleanly bypass the caching mechanism entirely, not least because the module id becomes the resolved filepath, not the string passed to require(), so we need to track filepaths to delete from cache. Any ideas?
@hacklikecrack: Use require.resolve() to find the ID. And, see the Node source code in module.js.
Thanks @SLaks. I'm posting here because I haven't yet managed to extract the relevant code from module.js. Will persevere and post any findings.
@hacklikecrack: Ripping large chunks of code from module.js isn't a good idea; for example, it will make you very sensitive to implementation changes. What's wrong with deleting from cache?
For example, as I'm not a big fan of dependency injection, under test I prefer to use the dependency resolution framework itself (in case of node.js, its CommonJS implementation) to mock out dependencies up front....
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.