2

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?

Ben Aston
  • 45,997
  • 54
  • 176
  • 303

1 Answers1

4

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

Benjamin Gruenbaum
  • 246,787
  • 79
  • 474
  • 476
  • 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) – Ben Aston Apr 26 '15 at 12:29
  • 1
    @BenAston yes, but overly descriptive, it's enough to say it's loaded, parsed, cached and executed. – Benjamin Gruenbaum Apr 26 '15 at 12:38
  • Does my description imply activities that do not occur? – Ben Aston Apr 26 '15 at 12:41
  • 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 – Benjamin Gruenbaum Apr 26 '15 at 12:42