Node.js 速查表
本页面汇总了 Node.js 开发中最常用的语法和知识点,方便快速查阅。
常用内置模块
// 文件系统
const fs = require('node:fs');
const fsPromises = require('node:fs/promises');
// HTTP
const http = require('node:http');
const https = require('node:https');
// 路径处理
const path = require('node:path');
// 事件
const EventEmitter = require('node:events');
// 流
const { Readable, Writable, Duplex, Transform } = require('node:stream');
// 子进程
const { exec, spawn, fork } = require('node:child_process');
// 实用工具
const util = require('node:util');
// 加密
const crypto = require('node:crypto');
// 操作系统
const os = require('node:os');
// URL 处理
const url = require('node:url');
文件操作
读取文件
// 同步
const data = fs.readFileSync('file.txt', 'utf8');
// 回调
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Promise
const data = await fsPromises.readFile('file.txt', 'utf8');
写入文件
// 同步
fs.writeFileSync('file.txt', 'content');
// 回调
fs.writeFile('file.txt', 'content', (err) => {
if (err) throw err;
});
// Promise
await fsPromises.writeFile('file.txt', 'content');
// 追加
fs.appendFileSync('file.txt', '\nnew line');
目录操作
// 创建目录
fs.mkdirSync('dir', { recursive: true });
// 读取目录
const files = fs.readdirSync('dir');
// 删除目录
fs.rmSync('dir', { recursive: true, force: true });
// 检查是否存在
fs.existsSync('path');
HTTP 服务器
创建服务器
const http = require('node:http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Hello' }));
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
请求信息
// 方法
req.method // 'GET', 'POST', etc.
// URL
req.url // '/path?query=value'
// 请求头
req.headers['content-type']
// 请求体
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => console.log(body));
响应方法
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('chunk');
res.end('final chunk');
路径处理
const path = require('node:path');
path.join('/a', 'b', 'c') // '/a/b/c'
path.resolve('file.txt') // 绝对路径
path.basename('/a/b/file.txt') // 'file.txt'
path.dirname('/a/b/file.txt') // '/a/b'
path.extname('file.txt') // '.txt'
path.parse('/a/b/file.txt') // { root, dir, base, ext, name }
事件
const EventEmitter = require('node:events');
const emitter = new EventEmitter();
// 注册监听器
emitter.on('event', (data) => console.log(data));
// 一次性监听器
emitter.once('event', () => {});
// 触发事件
emitter.emit('event', { key: 'value' });
// 移除监听器
emitter.off('event', listener);
// 移除所有监听器
emitter.removeAllListeners('event');
流
可读流
const readStream = fs.createReadStream('file.txt');
readStream.on('data', (chunk) => {
console.log(chunk);
});
readStream.on('end', () => {
console.log('Done');
});
可写流
const writeStream = fs.createWriteStream('output.txt');
writeStream.write('data');
writeStream.end();
writeStream.on('finish', () => {
console.log('Written');
});
管道
// 复制文件
fs.createReadStream('source.txt')
.pipe(fs.createWriteStream('dest.txt'));
// 使用 pipeline
const { pipeline } = require('node:stream/promises');
await pipeline(
fs.createReadStream('source.txt'),
fs.createWriteStream('dest.txt')
);
Promise 与异步
promisify
const util = require('node:util');
const readFile = util.promisify(fs.readFile);
const data = await readFile('file.txt', 'utf8');
Promise 静态方法
// 等待所有完成
await Promise.all([p1, p2, p3]);
// 等待所有结果
await Promise.allSettled([p1, p2, p3]);
// 第一个完成
await Promise.race([p1, p2, p3]);
// 第一个成功
await Promise.any([p1, p2, p3]);
进程信息
// 进程参数
process.argv // 命令行参数
process.env // 环境变量
process.cwd() // 当前工作目录
// 进程控制
process.exit(0) // 退出
process.nextTick(fn) // 下一个事件循环执行
// 信号处理
process.on('SIGTERM', () => {
// 优雅关闭
});
module.exports 导出
// 导出单个值
module.exports = function() {};
// 导出对象
module.exports = {
method1,
method2,
};
// 逐个导出
exports.method1 = method1;
exports.method2 = method2;
ES Modules 导入导出
// 导出
export const name = 'value';
export default class MyClass {}
// 导入
import { name } from './module.js';
import MyClass from './module.js';
import * as module from './module.js';
// 动态导入
const module = await import('./module.js');
package.json scripts
{
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "node --test",
"build": "tsc"
}
}
npm 常用命令
# 安装依赖
npm install
npm install package-name
npm install -D package-name
# 运行脚本
npm run start
npm test
# 更新依赖
npm update
npm outdated
# 发布包
npm publish
npm version patch/minor/major
常用状态码
| 状态码 | 含义 |
|---|---|
| 200 | OK |
| 201 | Created |
| 204 | No Content |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
调试技巧
# 启用调试
node --inspect app.js
# 等待调试器连接
node --inspect-brk app.js
# 查看内存使用
node --expose-gc app.js
性能监控
// 内存使用
const used = process.memoryUsage();
console.log({
heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)} MB`,
heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)} MB`,
});
// CPU 使用
const cpuUsage = process.cpuUsage();