The sequence of steps
- Resolving: get the absolute path of the module.
- Loading: load the module
- Wrapping: give a separate scope to your variables.
- Evaluating: is what the VM(usually V8)eventually does with the code
- Caching: cache the module in case we use it again.
What happens when we require a module?
To find out how requiring a module works, we can use or we type
module in REPL mode. The
module is available in the global object.
If I use this line of code:
const test = require("tetsModule") Node.js will look at places in paths array to find this module.
- At the first step, it looks in the current folder’s node_modules and if it couldn’t find the module it will look at parent folders step by step.
- After that, Node.js will look at
.node_modulesfolder in your home folder if you use Linux or Mac.
- At last, it looks at the folder which is Node.js is located
These are steps to find the location of non-core modules. core modules are the exception and Node.js find them immediately.
Is it possible to only resolve a module and not execute it?
The answer is yes and to do this we need to use
const m = require.resolve("myModuleName");
What is the usage?
It helps you check that the module exists or not.
Requiring modules with relative and absolute paths
To use relative path we need to start with
an example :
const test = require("./testFolder/myFile.js")
To use absolute path we need to start with
const test = require('/home/poorshad/Desktop/myfile.js')
What happens if we require two modules inside each other?
In Node.js circular reference is allowed and we can refer to modules like the code below:
If we run
Test.js with Node.js the result will be this in terminal:
We have imported
f1.js inside the
Test.js so it is the first module that has to be loaded and the first log in the console is
it is f1.
f1.js we have imported
f2.js and as a result, we can see
this is f2 in console.
When we log
f2.js f1 module has not exported it’s variables yet and we get an empty object on the console. After this console log
f2module exports, it’s variables in lines 4 and 5 of its code. Now, the module
f2is fully loaded.
Node.js continues with line 3 of
f1.js and since
f2.js is loaded it shows
 as the value of this module in the console.
Finally, we can see the console log of
Test.js in the last line of the console.
How the `require` handle file extensions when we require a file without extension?
for example, we have this line of code :
const myFile = require("./myFile");
This is the order that Node.js will do: