In the browser, the DOM is parsed and scripts are loaded and parsed in the order they are defined.
In Node.js, how are scripts loaded into memory?
Is the entire graph of scripts defined by the require
statements in each file traversed at initialisation-time, with the resulting objects and values hydrating the stack and heap ready for execution to start?
Synchronously. Whenever it encounters a require
it synchronously loads the script and runs it - then, when other scripts are found it synchronously loads them.
IIRC in the 0.2 days there was an asynchronous version but it's not here for a long time. As for what it actually does:
Basically, what it does is a fs.readFileSync
.
More specifically - Calling require
calls _load
which in turn first checks the cache and then it creates the module and it calls the relevant extension. Since multiple extensions are allowed (for example .json
) it loads each one differently, in the .js
case which is the common case it just calls fs.readFileSync
and then compiles it (which involves wrapping it, injecting exports and running it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With