Node.js 最常用的 5 个核心模块

Node.js 模块本质上是一组可包含在应用程序中的 JavaScript 函数或对象。Node 模块可让您将代码分解为更小、可重复使用的部分。
核心模块:
这些模块内置于 Node.js 中,并提供基本功能,例如 `fs`(文件系统)、`http`(HTTP 服务器/客户端)、`path`、`url` 等。您可以使用 `require()`
这是开发人员在其项目中使用的最常用的核心模块。
1. 路径
Node.js 中的“path”模块提供了处理文件和目录路径的实用程序。以下是“path”模块中最常用的一些方法。
路径.join()
将多个路径段组合成单个路径。它规范化生成的路径,处理多余的斜线或相对路径
const path = require('path'); const filePath = path.join('/users', 'john', 'documents', 'file.txt'); console.log(filePath); // Output: /users/john/documents/file.txt
路径.resolve()
从当前工作目录开始,将一系列路径或路径段解析为绝对路径。
const absolutePath = path.resolve('documents', 'file.txt'); console.log(absolutePath); // Output: /your/current/working/directory/documents/file.txt
路径.basename()
返回路径的最后一部分,通常是文件名。您还可以指定要从结果中删除的扩展名。
const fullPath = '/users/john/file.txt'; console.log(path.basename(fullPath)); // Output: file.txt console.log(path.basename(fullPath, '.txt')); // Output: file
路径.目录名()
返回路径的目录部分。
const filePath = '/users/john/documents/file.txt'; console.log(path.dirname(filePath)); // Output: /users/john/documents
路径.扩展名()
返回路径中文件的扩展名,包括点 (.)。
const filePath = '/users/john/documents/file.txt'; console.log(path.dirname(filePath)); // Output: /users/john/documents
路径.解析()
返回具有代表路径不同部分的属性的对象
const parsedPath = path.parse('/users/john/file.txt'); console.log(parsedPath); /* Output: { root: '/', dir: '/users/john', base: 'file.txt', ext: '.txt', name: 'file' } */
路径.isAbsolute()
检查路径是否是绝对路径,即从根目录(UNIX 上为 / 或 Windows 上为 C:\)开始。
console.log(path.isAbsolute('/users/john')); // Output: true console.log(path.isAbsolute('file.txt')); // Output: false
您可以使用更多方法,检查路径模块的官方文档
2. fs(文件系统)
Node.js 中的 fs(文件系统)模块允许您与文件系统交互以读取、写入和操作文件和目录。以下是 fs 模块中最常用的一些方法
fs.readFile() 和 fs.readFileSync()
异步和同步读取文件内容。
const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); const data = fs.readFileSync('example.txt', 'utf8'); console.log(data);
fs.writeFile() 和 fs.writeFileSync()
异步和同步地将数据写入文件。
fs.writeFile('example.txt', 'Hello, World!', (err) => { if (err) throw err; console.log('File written successfully'); }); fs.writeFileSync('example.txt', 'Hello, World!'); console.log('File written successfully');
fs.appendFile() & fs.appendFile()
异步和同步地将数据附加到文件。
fs.appendFile('example.txt', 'Hello, World!', (err) => { if (err) throw err; console.log('File written successfully'); }); fs.appendFileSync('example.txt', 'Hello, World!'); console.log('File written successfully');
fs.rename() 和 fs.renameSync()
异步和同步重命名或移动文件。
fs.rename('example.txt', 'renamed.txt', (err) => { if (err) throw err; console.log('File renamed successfully'); }); fs.renameSync('example.txt', 'renamed.txt'); console.log('File renamed successfully');
fs.unlink() 和 fs.unlinkSync()
异步和同步删除文件。
fs.unlink('example.txt', (err) => { if (err) throw err; console.log('File deleted'); }); fs.unlinkSync('example.txt'); console.log('File deleted');
fs.mkdir() 和 fs.mkdirSync()
异步和同步创建新目录。
fs.mkdir('newDirectory', (err) => { if (err) throw err; console.log('Directory created'); }); fs.mkdirSync('newDirectory'); console.log('Directory created');
fs.existsSync()
同步检查文件或目录是否存在。
const exists = fs.existsSync('example.txt'); console.log(exists ? 'File exists' : 'File does not exist');
fs.复制文件()
将文件从一个位置异步复制到另一个位置。
fs.copyFile('source.txt', 'destination.txt', (err) => { if (err) throw err; console.log('File copied successfully'); });
您可以使用更多方法,查看 fs 模块的官方文档
3. 事件
Node.js 中的 events 模块对于实现事件驱动编程至关重要。它允许您创建、监听和管理自定义事件。此模块中最常用的类是 `EventEmitter`,它提供了处理事件的各种方法。以下是一些最常用的方法:
发射器.on()
为特定事件注册侦听器(回调函数)。可以为单个事件注册多个侦听器。
发射器.发射()
发出特定事件,触发为该事件注册的所有侦听器。您可以向侦听器传递参数。
const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('greet', (name) => { console.log(`Hello, ${name}!`); }); emitter.emit('greet', 'Alice'); // Output: Hello, Alice!
发射器.once()
为仅调用一次的事件注册一个侦听器。事件发出后,侦听器将自动删除。
emitter.once('welcome', (name) => { console.log(`Welcome, ${name}!`); }); emitter.emit('welcome', 'Alice'); // Output: Welcome, Alice! emitter.emit('welcome', 'Bob'); // No output (listener is removed after first call)
发射器.removeAllListeners()
删除特定事件的所有监听器;如果未指定事件,则删除所有事件的监听器。
emitter.on('goodbye', () => console.log('Goodbye!')); emitter.removeAllListeners('goodbye');
您可以使用更多方法查看事件模块的官方文档
4. URL()
Node.js 中的 url 模块提供了用于 URL 解析、格式化和解析的实用程序。此模块对于处理和操作 Web 应用程序中的 URL 字符串非常有用。
新的 URL()
创建一个新的 URL 对象,它解析给定的 URL 并提供对其组件的访问。
URL.搜索参数
创建一个新的 URL 对象,它解析给定的 URL 并提供对其组件的访问。
const { URL } = require('url'); const myUrl = new URL('https://example.com/path?name=John&age=30'); console.log(myUrl.searchParams.get('name')); // Output: John
URL.toString() 和 URL.toJSON()
将 URL 对象转换为字符串表示形式。将 URL 序列化为 JSON 字符串
const { URL } = require('url'); const myUrl = new URL('https://example.com/path?name=John'); console.log(myUrl.toString()); // Output: https://example.com/path?name=John console.log(myUrl.toJSON()); // Output: "https://example.com/path?name=John"
URL.主机名 & URL.端口
获取或设置 URL 的主机名部分(不含端口)。获取或设置 URL 的端口部分。
const { URL } = require('url'); const myUrl = new URL('https://example.com:8000/path?name=John'); console.log(myUrl.hostname); // Output: example.com console.log(myUrl.port); // Output: 8000
还有更多方法可以使用,请查看 url 模块的官方文档
5. http
Node.js 中的 http 模块提供了创建和处理 HTTP 请求和响应的功能。以下是 http 模块中最常用的一些方法:
http.createServer()
创建一个用于监听传入请求的 HTTP 服务器。此方法返回 http.Server 的一个实例。
服务器.listen()
启动 HTTP 服务器并在指定的端口和主机上监听请求。
服务器.关闭()
停止服务器接受新连接并关闭现有连接。
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); server.listen(3000, () => { console.log('Server is running on http://localhost:3000'); }); server.close(() => { console.log('Server has been closed'); });
还有更多方法可以使用,请查看 http 模块的官方文档