4

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?

7
  • 1
    No. How could it possibly be traversed at initialization time before things start asking for other things? Think about it. Commented Apr 25, 2015 at 13:47
  • 1
    require is a dynamically executed function, it is not statically analysed. Read the source! Commented Apr 25, 2015 at 13:57
  • 1
    See also this detailed breakdown of how modules are loaded Commented Apr 25, 2015 at 14:04
  • @Bergi isn't that a much better duplicate target? Commented Apr 25, 2015 at 14:05
  • @BenjaminGruenbaum Maybe. However, even is the answer is marvelous, that question is a completely different one. I'm never sure how to proceed in such cases… Feel free to use your hammer. Commented Apr 25, 2015 at 14:07

1 Answer 1

6

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).

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

4 Comments

Would it be correct to say at a high level, once a script is retrieved, it is pulled into a cache, parsed by the JavaScript runtime into an abstract syntax tree; which is then evaluated resulting in hydration of the data structures of the runtime (the stack and heap)
@BenAston yes, but overly descriptive, it's enough to say it's loaded, parsed, cached and executed.
Does my description imply activities that do not occur?
No, it does not - it just gives equal emphasis to engine bits (like parsing, ast, compilation etc) and to actual loading - where the former also happens in a regular eval call. If you understand all that you're good to go

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.