I was just trying to understand modules in node. I understood few things like node creates a module wrapper function around code placed in each file.
Let's say there are 2 files, a.js and b.js
In a.js, when i require b.js for first time, how will the module wrapper function which is present in b.js get's executed.
Does node do something like, get the whole content of b.js file as a string and then execute that from a.js using eval
and then keep the result of this function call in cache.
More or less.
Node.js loads script file contents and wraps with module wrapper:
Module.wrap = function(script) {
return Module.wrapper[0] + script + Module.wrapper[1];
};
Module.wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'\n});'
];
Then module function is evaluated with vm.runInThisContext
:
var wrapper = Module.wrap(content);
var compiledWrapper = vm.runInThisContext(wrapper, {
filename: filename,
lineOffset: 0,
displayErrors: true
});
vm
module provides V8 execution context, and vm.runInThisContext
evaluates the code similarly to indirect eval
:
vm.runInThisContext() compiles code, runs it within the context of the current global and returns the result. Running code does not have access to local scope, but does have access to the current global object.
<...>
Because vm.runInThisContext() does not have access to the local scope, localVar is unchanged. In contrast, eval() does have access to the local scope, so the value localVar is changed. In this way vm.runInThisContext() is much like an indirect eval() call, e.g. (0,eval)('code').
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments