Skip to content

文件系统

node:fs 提供回调、同步和 Promise API。新代码优先使用 node:fs/promises;同步 API 仅适合启动脚本、CLI 等不影响并发请求的场景。

js
import { mkdir, readFile, writeFile } from 'node:fs/promises'

await mkdir('data', { recursive: true })
await writeFile('data/config.json', JSON.stringify({ enabled: true }), 'utf8')
const config = JSON.parse(await readFile('data/config.json', 'utf8'))

常用操作

目标API
读取 / 写入整个文件readFile / writeFile
追加appendFile
创建目录mkdir(path, { recursive: true })
删除文件 / 目录unlink / rm
移动或重命名rename
查询元信息stat / lstat
遍历目录readdir / opendir
大文件处理createReadStream / createWriteStream

路径与安全

用户输入不能直接拼接为文件路径。将其解析后限制在预期根目录内,防止 ../ 路径遍历;符号链接场景还需评估真实路径与访问权限。

js
import path from 'node:path'

const root = path.resolve('uploads')
const target = path.resolve(root, userInput)

if (!target.startsWith(`${root}${path.sep}`)) {
  throw new Error('非法文件路径')
}

文件存在性检查与后续操作之间可能发生变化(TOCTOU)。能直接执行操作时,不要先 access() 再操作;捕获并处理实际操作的错误。

基于 MIT 许可发布