推荐直接使用 Node.js 内置的 fs.promises API(v10+ 默认可用),它已提供完整、标准的 Promise 版本,无需手动封装;若需兼容旧版或增强功能,可用 util.promisify 或自定义工具函数。

用 Promise 封装 Node.js 的 fs 模块,核心是把回调风格的 API 转成返回 Promise 的函数,推荐直接使用 Node.js 内置的 fs.promises API(v10+ 默认可用),它已提供完整、标准的 Promise 版本,无需手动封装。
直接使用 fs.promises(最推荐)
fs.promises 是 Node.js 官方提供的 Promise 化接口,与原生 fs 方法一一对应,语义清晰、错误自动 reject、支持 async/await:
-
fs.promises.readFile(path, options?)—— 读取文件,返回Promise<Buffer | string> -
fs.promises.writeFile(path, data, options?)—— 写入文件,成功则 resolve,失败 reject -
fs.promises.appendFile(path, data, options?)—— 追加内容 -
fs.promises.access(path, mode?)、fs.promises.stat(path)、fs.promises.unlink(path)等均可用
示例:
const fs = require('fs');
async function handleFile() {
try {
const content = await fs.promises.readFile('./data.txt', 'utf8');
console.log(content);
await fs.promises.writeFile('./output.txt', 'Hello from fs.promises!');
console.log('写入完成');
} catch (err) {
console.error('操作失败:', err.message);
}
}
兼容旧版本或自定义封装(如需控制参数/日志)
若需在 Node.js < 10 或想统一拦截错误、添加重试、打日志等,可用 util.promisify 快速包装单个方法:
ZenHeart zenlink 与 zenlink-mcp 为 OpenClaw,涵盖安装、MCP 注册、钩子接线、入站轮询及升级维护。
立即学习“Java免费学习笔记(深入)”;
const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const unlink = promisify(fs.unlink);
// 使用方式一致
async function example() {
const data = await readFile('./config.json', 'utf8');
await writeFile('./backup.json', data);
}
注意:promisify 要求原函数最后一个参数是 (err, result) => {} 形式,fs 所有回调版方法都满足该约定。
封装成工具函数(增强健壮性)
可进一步封装常用逻辑,比如“安全读取 JSON”或“确保目录存在再写入”:
const fs = require('fs').promises;
const path = require('path');
// 安全读取 JSON 文件
async function readJSON(filePath) {
const content = await fs.readFile(filePath, 'utf8');
try {
return JSON.parse(content);
} catch (e) {
throw new Error(`解析 ${filePath} 失败:${e.message}`);
}
}
// 确保父目录存在后写入
async function writeSafe(filePath, data) {
const dir = path.dirname(filePath);
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(filePath, data);
}
注意事项
- 避免混用
fs(回调)和fs.promises(Promise)—— 同一项目建议统一风格 -
fs.promises不支持同步方法(如readFileSync),同步需求仍用原fs模块 - 错误始终以
reject抛出,无需手动throw;但需用try/catch或.catch()处理 - 大文件读写建议配合
stream(如fs.createReadStream),而非一次性readFile,避免内存溢出

















