Node.js 核心模块实践
2025/9/17大约 4 分钟
Node.js 核心模块实践
学习目标
本章将带你探索 Node.js 中一些最常用和最重要的核心模块。学完后,你将能够利用它们进行文件操作、路径处理和构建基础的 Web 服务。
Node.js 提供了一套功能强大的内置模块,无需额外安装即可直接使用。我们只需通过 require()
函数引入它们。
1. fs
模块:与文件系统交互
fs
(File System) 模块是 Node.js 中用于与文件系统进行交互的核心工具。它提供了丰富的函数来执行文件和目录的读、写、创建等操作。
读取文件
fs
模块提供了同步和异步两种方式来读取文件。
- 异步读取 (
fs.readFile
):这是推荐的方式,因为它不会阻塞事件循环。
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('读取文件时发生错误:', err);
return;
}
console.log('文件内容:', data);
});
console.log('发起读取文件请求后,我立即执行。');
- 同步读取 (
fs.readFileSync
):此方法会阻塞后续代码的执行,直到文件读取完成。仅在脚本启动时加载配置等少数场景下使用。
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('同步读取的文件内容:', data);
} catch (err) {
console.error('同步读取文件时发生错误:', err);
}
console.log('我必须等待文件读取完成才能执行。');
写入文件
同样,写入文件也有异步和同步两种方式。
- 异步写入 (
fs.writeFile
):将内容异步地写入文件。如果文件已存在,其内容将被覆盖。
const fs = require('fs');
const content = '这是将要写入文件的新内容。';
fs.writeFile('new-file.txt', content, 'utf8', (err) => {
if (err) {
console.error('写入文件时发生错误:', err);
return;
}
console.log('文件已成功写入!');
});
2. path
模块:处理文件路径
在不同操作系统中(Windows, macOS, Linux),文件路径的表示方式有所不同(例如,Windows 使用 \
而其他系统使用 /
)。path
模块提供了一套跨平台的工具来处理和转换文件路径。
路径拼接
path.join()
是一个安全且可靠的方法,用于将多个路径片段连接成一个规范化的路径。
const path = require('path');
const userDir = 'users';
const dataFile = 'data.json';
// 自动使用当前操作系统的正确分隔符
const fullPath = path.join('/home', userDir, dataFile);
console.log(fullPath); // 在 Linux/macOS 上输出: /home/users/data.json
// 在 Windows 上输出: \home\users\data.json
获取文件名和扩展名
path
模块还可以轻松地从一个完整路径中提取特定部分。
const path = require('path');
const filePath = '/home/users/profile.jpg';
console.log('文件名:', path.basename(filePath)); // 输出: profile.jpg
console.log('目录名:', path.dirname(filePath)); // 输出: /home/users
console.log('扩展名:', path.extname(filePath)); // 输出: .jpg
3. http
模块:创建 Web 服务器
我们在上一章已经初步接触了 http
模块。它是构建 Node.js Web 应用的基础,可以用来创建 HTTP 服务器和客户端。
让我们创建一个更具交互性的服务器,它能根据不同的 URL 请求返回不同的内容。
const http = require('http');
const server = http.createServer((req, res) => {
// req.url 包含了请求的 URL 路径
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>欢迎来到首页</h1>');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h2>这是关于我们页面</h2>');
} else {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 - 页面未找到</h1>');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`服务器正在 http://localhost:${port} 上运行`);
});
如何测试?
- 运行
node your-server-file.js
。 - 在浏览器中访问
http://localhost:3000
,你会看到首页内容。 - 访问
http://localhost:3000/about
,你会看到“关于我们”的内容。 - 访问任何其他路径,如
http://localhost:3000/contact
,则会显示 404 错误。
总结
在本章中,我们掌握了三个核心模块的基本用法:
- ✅
fs
模块:用于执行文件的异步和同步读写操作。 - ✅
path
模块:以跨平台的方式处理文件路径。 - ✅
http
模块:创建能处理基本路由的 HTTP 服务器。
下一步
虽然核心模块很强大,但在实际开发中,我们通常会使用社区开发的包来提高效率。下一章,我们将学习 Node.js 的包管理器 npm
以及如何使用流行的 Express
框架来简化 Web 开发。