跳到主要内容

Node.js

Node.js 是基于 V8 引擎的服务端 JavaScript 运行时,采用事件驱动与非阻塞 I/O 模型。

模块系统:CommonJS 与 ESM

CommonJS 使用 requiremodule.exports,同步加载,Node 早期默认方案。ESM 使用 importexport,静态分析,异步加载。在 package.json"type": "module" 可启用 ESM,或使用 .mjs 扩展名。

npm 常用命令

npm init 初始化项目;npm install <pkg> 安装依赖(写入 dependencies);npm install -D 安装开发依赖;npm run <script> 执行 package.json 中的脚本;npm update 更新依赖;npx 可直接运行包内可执行文件。

事件循环与浏览器差异

Node.js 事件循环分阶段:timerspending callbacksidle/preparepollcheckclose callbacksprocess.nextTickPromise.then(微任务)在每个阶段后执行,process.nextTick 优先于微任务。

Buffer

Buffer 用于处理二进制数据,是 Uint8Array 的子类。常用于文件 I/O、网络流、编码转换。创建方式包括 Buffer.from()Buffer.alloc()Buffer.allocUnsafe()

Stream

Stream 是 Node 处理大数据的核心抽象,分为 ReadableWritableDuplexTransform 四种。pipe 方法串联读写流,pipeline 提供更安全的错误处理。

import { createReadStream, createWriteStream } from 'fs';
import { pipeline } from 'stream/promises';

await pipeline(
createReadStream('input.txt'),
createWriteStream('output.txt')
);

常用内置模块

fs 文件系统,提供 readFilewriteFilecreateReadStream 等;path 处理路径拼接与解析;http 创建 HTTP 服务,核心是 http.createServerreq/res 对象;url 解析 URL;os 获取操作系统信息;crypto 提供加密、哈希能力。