目录
1. 介绍
Node.js 采用模块化的方式组织代码,使得开发更加清晰、可维护,并且可以重复利用已有的代码。Node.js 模块主要分为以下几类:
- 核心模块(Built-in Modules):Node.js 内置的模块,如
fs
、http
、path
、os
等,直接通过require()
引入即可使用。 - 第三方模块(Third-party Modules):通过
npm
安装的模块,如express
、axios
等,需要安装后再require()
引入。 - 自定义模块(Custom Modules):开发者自己编写的模块,通常是一个 JavaScript 文件,通过
module.exports
或exports
导出。
require()
是 Node.js 中用于加载模块的函数,可以引入核心模块、第三方模块和自定义模块。
2. 模块的分类及 require
使用示例
1. 核心模块
核心模块是 Node.js 直接提供的功能,直接用 require()
引入,无需安装。
示例(文件名:core_module.js
):
// 引入 Node.js 的 fs(文件系统)核心模块
const fs = require('fs');
// 使用 fs 模块读取当前目录下的文件
fs.readdir('.', (err, files) => {
if (err) {
console.error('读取目录失败', err);
} else {
console.log('当前目录下的文件:', files);
}
});
运行结果:
当前目录下的文件: [ 'core_module.js', 'custom_module.js', 'third_party_module.js' ]
2. 第三方模块
第三方模块需要使用 npm install
进行安装后才能使用。
示例:使用 axios
进行 HTTP 请求(文件名:third_party_module.js
)
// 先安装 axios: npm install axios
const axios = require('axios');
// 发送 GET 请求
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('获取的数据:', response.data);
})
.catch(error => {
console.error('请求失败', error);
});
运行结果:
获取的数据: { userId: 1, id: 1, title: '...', body: '...' }
3. 自定义模块
自定义模块是开发者自己编写的 JavaScript 文件,使用 module.exports
导出。
步骤:
- 创建一个数学计算模块
math.js
- 在主文件
custom_module.js
中引入并使用
文件 1(文件名:math.js
,用于导出功能)
// 自定义模块,提供数学计算方法
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
// 使用 module.exports 导出模块
module.exports = {
add,
subtract
};
文件 2(文件名:custom_module.js
,用于引入并使用模块)
// 引入自定义模块
const math = require('./math'); // 需要加 './' 表示是自定义模块
console.log('加法结果:', math.add(10, 5)); // 输出:15
console.log('减法结果:', math.subtract(10, 5)); // 输出:5
运行结果:
加法结果: 15
减法结果: 5
3. require
的解析规则
在 require()
引入模块时,Node.js 会按以下顺序查找模块:
- 核心模块(如
fs
、http
),如果是核心模块,直接返回模块对象。 - 自定义模块,如果是
./
或../
开头的路径,Node.js 解析对应文件并加载。 - 第三方模块,Node.js 会从
node_modules
目录中查找模块,逐级向上查找(从当前目录开始,直到根目录)。
示例:
const fs = require('fs'); // 直接加载核心模块
const math = require('./math'); // 加载自定义模块
const axios = require('axios'); // 加载第三方模块(需要提前安装)
4. 总结
- 核心模块 直接
require()
使用,无需安装。 - 第三方模块 需使用
npm install 包名
安装后才能require()
使用。 - 自定义模块 通过
module.exports
或exports
导出,使用require('./模块路径')
引入。 require()
按以下顺序解析模块:- 核心模块
- 自定义模块(使用相对路径或绝对路径)
- 第三方模块(先查找
node_modules
目录)
通过本教程,大家应该能够清楚了解 Node.js 的模块分类,以及如何使用 require()
引入不同类型的模块,希望对大家的学习有所帮助!