使用 Node.js 写入文件
写入文件
在 Node.js 中向文件写入的最简单方法是使用 fs.writeFile()
API。
const = ('node:fs');
const = 'Some content!';
.('/Users/joe/test.txt', , => {
if () {
.();
} else {
// file written successfully
}
});
同步写入文件
或者,您可以使用同步版本 fs.writeFileSync()
const = ('node:fs');
const = 'Some content!';
try {
.('/Users/joe/test.txt', );
// file written successfully
} catch () {
.();
}
您还可以使用 fs/promises
模块提供的基于 promise 的 fsPromises.writeFile()
方法
const = ('node:fs/promises');
async function () {
try {
const = 'Some content!';
await .('/Users/joe/test.txt', );
} catch () {
.();
}
}
();
默认情况下,如果文件已存在,此 API 将替换文件内容。
您可以通过指定一个标志来修改默认行为
fs.writeFile('/Users/joe/test.txt', content, { : 'a+' }, => {});
您可能会用到的标志有
标志 | 描述 | 如果文件不存在则创建 |
---|---|---|
r+ | 此标志打开文件用于读取和写入 | ❌ |
w+ | 此标志打开文件用于读取和写入,并且它还将流定位在文件的开头 | ✅ |
a | 此标志打开文件用于写入,并且它还将流定位在文件的末尾 | ✅ |
a+ | 此标志打开文件用于读取和写入,并且它还将流定位在文件的末尾 | ✅ |
- 您可以在 fs 文档中找到有关标志的更多信息。
向文件追加内容
当您不想用新内容覆盖文件,而是想向其中添加内容时,追加到文件非常方便。
示例
一个方便的将内容追加到文件末尾的方法是 fs.appendFile()
(以及其对应的 fs.appendFileSync()
)
const = ('node:fs');
const = 'Some content!';
.('file.log', , => {
if () {
.();
} else {
// done!
}
});
使用 Promise 的示例
这是一个 fsPromises.appendFile()
的示例
const = ('node:fs/promises');
async function () {
try {
const = 'Some content!';
await .('/Users/joe/test.txt', );
} catch () {
.();
}
}
();