Reputation: 1859
I am new to Node.js, and while learning its basics, I came across some of its import syntax and semantics of the CJS system such as require()
, module.exports
and so on.
Now I have quite a few questions related to Node.js internals in this regard, but couldn't find any convincing answers out there, maybe because Node.js is still a relatively recent technology.
Q1) To achieve a local scope and keep all the global variables in a module private, why does Node.js use a function to wrap the module's code? Can't this local scope kind-of thing be implemented without using functions?
Q2) Why are 5 args passed to this wrapper function? Why can't they just be free variables of the wrapped function instead of being local to the function?
Q3) How does Node.js call this wrapper function? It seems to be an anonymous function, and as far as I know, there is no way to call an anonymous function unless it's saved in an identifier or is immediately invoked.
Q4) Are all require()
calls in a module resolved at compile time to save computation time, or are they resolved at runtime.
Upvotes: 0
Views: 51
Reputation: 324
Q1) To achieve a local scope and keep all the global variables in a module private, why does Node.js use a function to wrap the module's code? Can't this local scope kind-of thing be implemented without using functions?
An execution context of a function is the mechanism to create a local scope in JavaScript. Local variables of a function are unavailable outside of its execution context, unless you return them. The benefit of that is that the global scope doesn't get polluted with variables from different files.
Q2) Why are 5 args passed to this wrapper function? Why can't they just be free variables of the wrapped function instead of being local to the function?
There is a different instance of those 5 args that get passed on each function call.
Q3) How does Node.js call this wrapper function? It seems to be an anonymous function, and as far as I know, there is no way to call an anonymous function unless it's saved in an identifier or is immediately invoked.
There are multiple steps that happen after invoking require()
. Regarding your specific question - when Module.prototype._compile()
is called during the execution of require('file.js')
, it wraps the contents of file.js
in a function and then runs that function.
Q4) Are all require() calls in a module resolved at compile time to save computation time, or are they resolved at runtime.
Modules are cached on their first invocation with require()
. Every time you call require('file.js')
you get the same instance of file.js
.
Upvotes: 1