5 things that happen every time you require a file in Node.js

Nikhil Vijayan
Sep 2 · 1 min read
Image for post
Image for post

Every time you require a file in node, these are the 5 things that take place:

  • Resolve
  • Load
  • Wrap
  • Evaluate
  • Cache

Resolve

Node will attempt to map the string given to require() into a path on the file system. This path could be local to node, under nodule_modules folder, or node modules under a parent directory or any other path.

Load

Node will then load the contents of this file into memory

Wrap

Wraps the content of the file with an IIFE (I’ve discussed this IIFE in another blog post How require and module.exports in node works)

Evaluate

Node will then evaluate the file (for eg: using the V8 engine)

Cache

Once it’s done evaluating the file, it will cache it. The next time you require the same file, these steps will not happen and it will read it from the cache directly.

Note: I learned this thanks to Sameer Buna’s “You don’t know node” talk from ForwardJS San Francisco 2017.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store