Welcome to ciysys blog

The loading sequence for require() in Node.js

Published on: 18th Jun 2022

Overview

We are using require() for referencing the public functions in another module. Let's do some experiment on it and see how it works.

If a script file was required in multiple script files, how many times that it will be loaded?

Let's develop a simple app that handles the customer functions and supplier functions to find it out.

Explanations

  1. In index.js, app-shared.js is the first module that will be loaded into the memory.
  2. Upon loading app-shared.js into the memory, it will load app-cust.js and then app-supp.js. But, the console.log('this is app-shared.js') line will not be executed yet (it will be executed after all required() has been processed).
  3. Loads app-cust.js into the memory. Since this script does not reference to any other module, the console.log('this is app-cust.js') line will be executed. You may be treat it like a 'startup code' in that module.
  4. Loads app-supp.js into the memory. Again, since this script does not reference to any other module, the console.log('this is app-supp.js') line will be executed.
  5. Upon completed loading app-cust.js and app-supp.js, console.log('this is app-shared.js') in app-shared.js will be executed.
  6. Finally, console.log('done') line in index.js will be executed.

What if we fork the index.js or run index.js with worker?

All console.log() lines will appear multiple times that depends on how many time you fork the index.js.

References

Conclusion

require() is CommonJS module system. With the detail analysis on how the loading module works, it helps in writing a better startup script.

Jump to #NODEJS blog

Author

Lau Hon Wan, software developer.