最简洁方式是使用 fs.promises api 配合 async/await:readfile 读取(指定 'utf8' 得字符串)、writefile 覆盖写入、appendfile 追加写入,路径建议用 path.join(__dirname, ...),目录不存在时需先用 mkdir(..., {recursive: true}) 创建。

在 Node.js 环境中,用 async/await 读写文件最简洁的方式是配合 fs.promises API(Node.js 10.0+ 原生支持),无需手动包装 fs.readFile 等回调函数。
读取文件内容(async/await)
使用 fs.promises.readFile(),返回 Promise,可直接 await:
- 默认返回
Buffer,加encoding选项(如'utf8')得到字符串 - 路径需为绝对路径或相对于当前工作目录的相对路径;建议用
path.join(__dirname, 'xxx.txt')避免路径错误 - 必须用
try/catch捕获可能的错误(如文件不存在、权限不足)
const fs = require('fs').promises;
const path = require('path');
async function readTextFile() {
try {
const content = await fs.readFile(
path.join(__dirname, 'data.txt'),
'utf8'
);
console.log(content);
} catch (err) {
console.error('读取失败:', err.message);
}
}
写入文件内容(async/await)
fs.promises.writeFile() 会自动创建文件(含不存在的目录需额外处理),覆盖写入;若需追加,用 fs.promises.appendFile():
-
writeFile:清空原文件后写入新内容 -
appendFile:在文件末尾添加内容(文件不存在时会新建) - 同样推荐指定编码(如
'utf8'),避免乱码
async function writeTextFile() {
try {
await fs.writeFile(
path.join(__dirname, 'output.txt'),
'Hello, async world!\n',
'utf8'
);
console.log('写入成功');
} catch (err) {
console.error('写入失败:', err.message);
}
}
读写组合:读一个文件,处理后写入另一个
这是常见场景,比如读配置、修改字段、保存备份。利用 await 的顺序执行特性,逻辑清晰易维护:
- 先 await 读取原始内容
- 对数据做同步处理(如 JSON 解析、字符串替换、对象修改)
- 再 await 写入新文件或覆盖原文件
async function transformAndSave() {
try {
const raw = await fs.readFile('./config.json', 'utf8');
const config = JSON.parse(raw);
config.version = '2.1.0';
config.updatedAt = new Date().toISOString();
await fs.writeFile(
'./config-updated.json',
JSON.stringify(config, null, 2),
'utf8'
);
console.log('已生成更新后的配置文件');
} catch (err) {
console.error('处理失败:', err.message);
}
}
注意:目录不存在时需提前创建
writeFile 不会自动创建父目录。若路径含多层不存在的文件夹(如 ./logs/app/error.txt),需先调用 fs.promises.mkdir(..., { recursive: true }):
-
recursive: true表示递归创建所有上级目录 - 建议在写入前统一确保目录存在,避免
ENOENT错误
async function safeWrite() {
const filePath = path.join(__dirname, 'logs', 'app', 'report.txt');
const dirPath = path.dirname(filePath);
try {
await fs.mkdir(dirPath, { recursive: true });
await fs.writeFile(filePath, 'Report generated.', 'utf8');
} catch (err) {
console.error('安全写入失败:', err.message);
}
}
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











