Reputation: 1859
While going through the source of require()
in the GitHub repository for Node.js, I am surprised and confused by one thing:
The file loader.js that actually defines the require()
logic, uses require()
calls in itself.
How is this possible?
Is there some other code for the require()
calls used in the internals of Node.js, for e.g. all the require()
calls used in loader.js file.
I know that all require()
calls in a Node.js program that I write in a given editor, on my machine, are resolved using the Module.prototype.require
method declared in loader.js.
Upvotes: 2
Views: 371
Reputation: 8718
It seems like the actual base require
is defined here, in /internal/bootstrap/loaders.js
. This line makes use of [compileFunction][3]
in /lib/vm.js
. That again uses _compileFunction
which is defined as such:
const {
ContextifyScript,
MicrotaskQueue,
makeContext,
isContext: _isContext,
constants,
compileFunction: _compileFunction,
measureMemory: _measureMemory,
} = internalBinding('contextify');
Which, if we go back to /internal/bootstrap/loaders.js
, is defined as such:
let internalBinding;
{
const bindingObj = ObjectCreate(null);
// eslint-disable-next-line no-global-assign
internalBinding = function internalBinding(module) {
let mod = bindingObj[module];
if (typeof mod !== 'object') {
mod = bindingObj[module] = getInternalBinding(module);
ArrayPrototypePush(moduleLoadList, `Internal Binding ${module}`);
}
return mod;
};
}
And getInternalBinding
we find at the top of that file, in this comment:
// This file is compiled as if it's wrapped in a function with arguments
// passed by node::RunBootstrapping()
/* global process, getLinkedBinding, getInternalBinding, primordials */
Which brings an end to our tour here. So yes, there's still some code between the require()
defined in loader.js
and the actual C binding. As for what happens in C-land, I'm not sure myself.
Upvotes: 2