3

When exporting a module that has another dependency, is it best to include that dependency within the module export function or outside of it? I usually see the latter, but it seems like it would be best to keep it in the local scope.

For example:

var foo = require('foo');

module.exports = function(d) {
    return foo(d)/2;
}

vs.

module.exports = function(d) {
    var foo = require('foo');

    return foo(d)/2;
}

1 Answer 1

7

Only things exposed on module.exports and global can be accessed from other modules in node. Unlike in the browser, var creates a local reference. To quote from node's documentation:

In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.

The difference between the two versions is therefore minimal - the first incurs a lookup in the local scope, while the other hits require.cache every time the function is invoked. From what I have seen of node code, the former (var someVar = require('something');) seems to be preferred.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the great answer! My understanding is that the lookup in the local scope happens only once - when the function is defined. Is that true? If so, the former method makes the most sense. Otherwise, do you know how expensive a lookup in the local scope is compared to a hit to require.cache?
The scope lookup is likely to be the less intensive one - the lookup is dynamic (IIRC) but is almost certainly easier for the JITC to optimize than the lookup for require + the function call + the lookup in the require.cache.

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.