About
The import functionality implementation of commonjs (and then node) is done via the require function
require basically:
- reads a Javascript file (generally a CommonJs module but it may be any javascript file)
- executes it,
- and then return the exports object (or module.exports)
It is the built-in statement from the commonjs module format to load module.
Require vs Import
require permits to load CommonJs Module whereas the import statement permits to load ESM module
Node.js follows by default the commonJs format, if you want to use import, you need to:
- or use a transpiler (generally babel) to transform the Esm module into an CommonJs one (the import statement will then become require)
Syntax and High-level algorithm of require in Node
If the code is run directly on Node without any other tool, the require node function is used to resolve (find) the dependency.
The below require statement called from a module located at path Y
require(X)
where:
- X is an module id that can be:
- a file
Require will resolve the module location with the following algo:
- 1. If X is a core module,
- a. return the core module
- b. STOP
- 2. If X begins with /
- a. set Y to be the filesystem root
- 3. If X begins with ./ or / or ../, it indicates:
- a. a file: LOAD_AS_FILE(Y + X)LOAD_AS_FILE(Y + X
- b: a folder: LOAD_AS_DIRECTORY(Y + X)
- 4. otherwise try to load from:
- a folder in the NODE_PATH
- a node_modules folder.: LOAD_NODE_MODULES(X, dirname(Y))
- 5. THROW “not found”
More .. see high-level algorithm in pseudocode of what require.resolve() does
Dependency Cycle
Module File Extension
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions:
- .js (interpreted as JavaScript text files)
- .json (parsed as JSON text files)
- and finally .node. (interpreted as compiled addon modules loaded with dlopen)
Example
Node Module
Local Package installed with Javascript - npm (Node package manager)
var demo=require('package-name');
demo.printMsg
Project Module
- The module with two arrow javascript function.
const { PI } = Math;
exports.area = (r) => PI * r ** 2;
exports.circumference = (r) => 2 * PI * r;
- The client of the modules> By giving the path, node know that it's a project module
// loads the module circle.js that is in the same directory as foo.js.
const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);