Node.js 实用工具模块 (Utility Modules)
Node.js - 核心实用模块
Section titled “Node.js - 核心实用模块”Node.js 提供了一套丰富的内置模块,它们提供了应用程序开发中经常需要的基本实用工具。这些模块不需要通过 npm 安装;你可以直接使用 require() 来调用它们。
| 序号 | 模块名称 | 描述 | 示例代码片段 |
|---|---|---|---|
| 1 | os 模块 | 提供与底层操作系统相关的方法和属性。对于获取操作系统类型、平台、CPU 架构、内存使用情况、网络接口等信息非常有用。 | const os = require('os');console.log('Platform:', os.platform()); // 例如:'win32', 'linux', 'darwin'console.log('Free Memory:', os.freemem()); |
| 2 | path 模块 | 提供跨平台处理文件和目录路径的实用工具。对于构造、解析和规范化路径至关重要。 | const path = require('path');const fullPath = path.join(__dirname, 'data', 'file.txt');console.log('File Extension:', path.extname(fullPath)); // '.txt'console.log('Directory Name:', path.dirname(fullPath)); |
| 3 | url 模块 | 提供 URL 解析和处理的实用工具。用于将 URL 分解为各个组成部分(协议、主机名、路径、查询参数)或构造 URL。 | const url = require('url');const myURL = new URL('https://example.com/path?query=value#hash');console.log('Hostname:', myURL.hostname); // 'example.com'console.log('Search Params:', myURL.searchParams.get('query')); // 'value' |
| 4 | util 模块 | 提供各种实用函数,包括 util.promisify(用于将基于回调的函数转换为基于 Promise 的函数)、util.inspect(用于详细的对象检查)以及用于类型检查的函数。 | const util = require('util');const fs = require('fs');const readFilePromise = util.promisify(fs.readFile);async function read() { const data = await readFilePromise('file.txt', 'utf8'); } |
| 5 | querystring 模块 | 提供用于解析和格式化 URL 查询字符串(例如,?key1=value1&key2=value2)的实用工具。通常与 http 模块一起使用或处理 URL 编码的数据。 | const querystring = require('querystring');const parsed = querystring.parse('name=Alice&city=Wonderland');console.log(parsed.city); // 'Wonderland'const stringified = querystring.stringify({ a: 1, b: 'two' }); // 'a=1&b=two' |
| 6 | assert 模块 | 提供一组断言函数,主要用于编写单元测试。如果断言失败,它会抛出一个 AssertionError。 | const assert = require('assert');assert.strictEqual(1 + 1, 2, 'Math failure!');// assert.strictEqual(1 + 1, 3); // 这行代码会抛出错误 |
其他在单独章节中介绍的重要核心模块包括 fs (文件系统)、http (HTTP 网络)、https (HTTPS 网络)、events (事件触发器)、stream (数据流) 和 child_process (子进程)。
注意:先前用于处理跨多个 I/O 操作的错误处理的 domain 模块现在已弃用,通常应避免使用。现代的错误处理模式、Promise,以及可能的 AsyncLocalStorage 提供了更好的替代方案。