使用 Node.js 写入文件

¥Writing files with Node.js

写入文件

¥Writing a file

在 Node.js 中写入文件的最简单方法是使用 fs.writeFile() API。

¥The easiest way to write to files in Node.js is to use the fs.writeFile() API.

const fs = require('node:fs');

const content = 'Some content!';

fs.writeFile('/Users/joe/test.txt', content, err => {
  if (err) {
    console.error(err);
  } else {
    // file written successfully
  }
});

同步写入文件

¥Writing a file synchronously

或者,你可以使用同步版本 fs.writeFileSync()

¥Alternatively, you can use the synchronous version fs.writeFileSync():

const fs = require('node:fs');

const content = 'Some content!';

try {
  fs.writeFileSync('/Users/joe/test.txt', content);
  // file written successfully
} catch (err) {
  console.error(err);
}

你还可以使用 fs/promises 模块提供的基于 promise 的 fsPromises.writeFile() 方法:

¥You can also use the promise-based fsPromises.writeFile() method offered by the fs/promises module:

const fs = require('node:fs/promises');

async function example() {
  try {
    const content = 'Some content!';
    await fs.writeFile('/Users/joe/test.txt', content);
  } catch (err) {
    console.log(err);
  }
}

example();

默认情况下,如果文件内容已经存在,此 API 将替换文件内容。

¥By default, this API will replace the contents of the file if it does already exist.

你可以通过指定标志来修改默认值:

¥You can modify the default by specifying a flag:

fs.writeFile('/Users/joe/test.txt', content, { flag: 'a+' }, err => {});

你可能使用的标志是

¥The flags you'll likely use are

标志描述如果文件不存在,则会创建它
r+此标志打开文件进行读写
w+此标志打开文件进行读写,并将流定位在文件开头
a此标志打开文件进行写入,并将流定位在文件末尾
a+此标志打开文件进行读写,并将流定位在文件末尾
  • 你可以在 fs 文档 中找到有关标志的更多信息。

    ¥You can find more information about the flags in the fs documentation.

将内容附加到文件

¥Appending content to a file

当你不想用新内容覆盖文件,而是想向文件中添加内容时,将内容附加到文件会非常方便。

¥Appending to files is handy when you don't want to overwrite a file with new content, but rather add to it.

示例

¥Examples

将内容附加到文件末尾的一种方便方法是 fs.appendFile()(及其 fs.appendFileSync() 对应项):

¥A handy method to append content to the end of a file is fs.appendFile() (and its fs.appendFileSync() counterpart):

const fs = require('node:fs');

const content = 'Some content!';

fs.appendFile('file.log', content, err => {
  if (err) {
    console.error(err);
  } else {
    // done!
  }
});

带有 Promises 的示例

¥Example with Promises

以下是 fsPromises.appendFile() 示例:

¥Here is a fsPromises.appendFile() example:

const fs = require('node:fs/promises');

async function example() {
  try {
    const content = 'Some content!';
    await fs.appendFile('/Users/joe/test.txt', content);
  } catch (err) {
    console.log(err);
  }
}

example();