Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Module System

The Node.js module system

The Node.js module system is one of its core features; it allows developers to organize code into small, reusable units called modules.

A module is an independent file that encapsulates a specific functionality and can be imported and used in other files.

The Node.js module system is an important foundation for building Node.js applications, enabling developers to split code into reusable, maintainable pieces.

Each module is a separate JavaScript file containing a set of related functions, objects, or variables. In this way, Node.js provides a structured approach to managing large applications, making code clearer and easier to maintain.

Every file in Node.js can serve as a module, and by default it is in an independent scope.

The module system follows the CommonJS specification but also supports ES modules.

Module Types

Node.js supports the following types of modules:


Importing Built-in Modules

Built-in modules are bundled with Node.js and are already included in the environment when Node.js is installed, so no additional installation is needed. Common built-in modules include fs, http, path, os, crypto, etc.

To import a built-in module, simply use the require() function with the module name. For example, to import the file system module fs, path, and http, you can do the following:


// Import filesystem module
const fs = require('fs');

// Import path module
const path = require('path');

// Import HTTP module
const http = require('http');

Here, fs is a string representing the name of the module to load. Node.js automatically recognizes it as a built-in module and loads the corresponding functionality.

Example

const

os

=

require

(

'os'

)

;

console.

log

(

'Operating System:'

,

os.

platform

(

)

)

;

console.

log

(

'Total Memory:'

,

os.

totalmem

(

)

)

;


Importing Third-Party Modules

Third-party modules are modules published by developers or the open-source community and can be installed into a project via npm (Node Package Manager). Common third-party modules include express, lodash, axios, etc.

Once a third-party module is installed, it is placed in the project's node_modules directory. To import a third-party module, likewise use the require() function, but pass the module's name. For example, to import the express framework, you can do the following:

// 导入第三方模块 express
const express = require('express');

Before importing a third-party module, make sure it has been installed via npm. For example, installing express can be done with the following command:


npm install express

Install the third-party module lodash and import it to test:

Example

const

lodash

=

require

(

'lodash'

)

;

const

array

=

[

1

,

2

,

3

,

4

]

;

const

reversedArray

=

lodash.

reverse

(

array.

slice

(

)

)

;

// Use lodash to reverse an array

console.

log

(

'Reversed Array:'

,

reversedArray

)

;


Custom Module Export and Import (CommonJS Modules)

**1. Exporting a Module:** Use module.exports or exports to export functions, objects, or variables.

**2. Importing a Module:** Use require() to import a module.

Import the module

In Node.js, importing a module is very simple. As shown below, we create a main.js file and import the hello module, with the following code:

main.js file code:

var

hello

=

require

(

'./hello'

)

;

hello.

world

(

)

;

In the example above, the code require('./hello') imports the hello.js file in the current directory (./ is the current directory; the default extension for node.js files is .js).

Node.js provides two objects, exports and require, where exports is the module's public interface and require is used to obtain a module's interface from outside, i.e., the exports object of the required module.

Next, let's create the hello.js file with the following code:

Code for the hello.js file:

exports.

world

=

function

(

)

{

    console.

log

(

'Hello World'

)

;

}

In the example above, hello.js exposes world as the module's access interface through the exports object; in main.js, this module is loaded via require('./hello'), and then you can directly access the exports object in hello.js.

Sometimes we just want to encapsulate an object in a module, in the following format:


module.exports = function() {
  // ...
}

For example:

Code for the hello.js file:

// hello.js

function

Hello

(

)

{

       

var

name

;

       

this

.

setName

=

function

(

thyName

)

{

                name

=

thyName

;

       

}

;

       

this

.

sayHello

=

function

(

)

{

                console.

log

(

'Hello '

name

)

;

       

}

;

}

;

module.

exports

=

Hello

;

This way you can obtain the object directly:

main.js file code:

// main.js

var

Hello

=

require

(

'./hello'

)

;

hello

=

new

Hello

(

)

;

hello.

setName

(

'BYVoid'

)

;

hello.

sayHello

(

)

;

The only change to the module interface is using module.exports = Hello instead of exports.world = function(){}. When the module is referenced externally, its interface object is the Hello object itself to be output, rather than the original exports.

The difference between module.exports and exports:


Custom Module Export and Import (ES Modules)

ES modules use import and export and are the modern JavaScript module specification.

Example

// myModule.mjs

export

function

greet

(

name

)

{

 

return

`Hello

,

$

{

name

}

!

`

;

}

// main.mjs

import

{

greet

}

from

'./myModule.mjs'

;

console.

log

(

greet

(

'Bob'

)

)

;

// Output: Hello, Bob!


Path Resolution When Loading Modules

**1. Core Modules:** Such as http and fs, included when Node.js is installed and can be loaded directly.


const http = require('http');

**2. Local File Modules:** Loaded using relative or absolute paths, requiring ./ or / to be specified.


const myModule = require('./myModule');

**3. Third-Party Modules:** Located in the node_modules directory; simply enter the module name to load it.


const express = require('express');

Module Caching

**Module Caching Mechanism:** Node.js caches loaded modules to improve performance. When the same module is require()'d again, the cached module is returned directly instead of being reloaded.

**Refreshing the Cache:** To reload a module, you can delete the cache:


delete require.cache[require.resolve('./myModule')];

Circular dependency

When two or more modules import each other, it is called a circular dependency. Node.js can handle simple circular dependencies, but may result in partially exported objects that are not fully initialized.

Example

// a.js

const

b

=

require

(

'./b'

)

;

console.

log

(

'a.js:'

,

b.

message

)

;

module.

exports

=

{

message

:

'Hello from a'

}

;

// b.js

const

a

=

require

(

'./a'

)

;

console.

log

(

'b.js:'

,

a.

message

)

;

module.

exports

=

{

message

:

'Hello from b'

}

;

// main.js

require

(

'./a'

)

;

The output shows that when b.js imports a.js, since a.js has not yet fully executed, a.message is undefined.


Module Wrapping and Scope

Node.js wraps each module in a function, giving each module an independent scope. Example:

// Node.js 内部将模块包装为类似这样的函数:
(function(exports, require, module, __filename, __dirname) {
  // Module code here
});

This means variables defined in a module do not pollute the global scope.


Where Are Server-Side Modules Placed

Perhaps you have noticed that we have already used modules in our code, like this:


var http = require("http");

...

http.createServer(...);

Node.js comes with a built-in module called http ; in our code we require it and assign the return value to a local variable.

This turns our local variable into an object with all the public methods provided by the http module.

The file lookup strategy of Node.js's require method is as follows:

Since there are 4 types of modules in Node.js (native modules and 3 types of file modules), although the require method is extremely simple, its internal loading is quite complex, with different loading priorities. As shown in the figure below:

Loading from the File Module Cache

Although native modules and file modules have different priorities, both preferentially load existing modules from the file module cache.

Loading from Native Modules

Native modules have priority second only to the file module cache. After resolving the filename, the require method first checks whether the module is in the list of native modules. Taking the http module as an example, even if an http/http.js/http.node/http.json file exists in the directory, require("http") will not be loaded from these files but from the native modules.

Native modules also have a cache, and loading from the cache is likewise prioritized. If it has not been loaded into the cache before, the native module's loading method is called to load and execute it.

Loading from Files

When a file module does not exist in the cache and is not a native module, Node.js parses the arguments passed to the require method and loads the actual file from the file system. The wrapping and compilation details during loading were introduced in the previous section; here we will describe in detail the process of finding file modules, among which there are also some details worth knowing.

The require method accepts the following types of parameters:

Execution order of the require(X) statement under path Y:


1. 如果 X 是内置模块
   a. 返回内置模块
   b. 停止执行
2. 如果 X 以 '/' 开头
   a. 设置 Y 为文件根路径
3. 如果 X 以 './' 或 '/' or '../' 开头
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
4. LOAD_NODE_MODULES(X, dirname(Y))
5. 抛出异常 "not found"

LOAD_AS_FILE(X)
1. 如果 X 是一个文件, 将 X 作为 JavaScript 文本载入并停止执行。
2. 如果 X.js 是一个文件, 将 X.js 作为 JavaScript 文本载入并停止执行。
3. 如果 X.json 是一个文件, 解析 X.json 为 JavaScript 对象并停止执行。
4. 如果 X.node 是一个文件, 将 X.node 作为二进制插件载入并停止执行。

LOAD_INDEX(X)
1. 如果 X/index.js 是一个文件,  将 X/index.js 作为 JavaScript 文本载入并停止执行。
2. 如果 X/index.json 是一个文件, 解析 X/index.json 为 JavaScript 对象并停止执行。
3. 如果 X/index.node 是一个文件,  将 X/index.node 作为二进制插件载入并停止执行。

LOAD_AS_DIRECTORY(X)
1. 如果 X/package.json 是一个文件,
   a. 解析 X/package.json, 并查找 "main" 字段。
   b. let M = X + (json main 字段)
   c. LOAD_AS_FILE(M)
   d. LOAD_INDEX(M)
2. LOAD_INDEX(X)

LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
   a. LOAD_AS_FILE(DIR/X)
   b. LOAD_AS_DIRECTORY(DIR/X)

NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let I = count of PARTS - 1
3. let DIRS = []
4. while I >= 0,
   a. if PARTS[I] = "node_modules" CONTINUE
   b. DIR = path join(PARTS[0 .. I] + "node_modules")
   c. DIRS = DIRS + DIR
   d. let I = I - 1
5. return DIRS

Usage of exports and module.exports

To expose properties or methods externally, use exports is fine; to expose an object (like a class, containing many properties and methods), use module.exports。