跳到内容

使用 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  = ('node:fs');

const  = 'Some content!';

.('/Users/joe/test.txt', ,  => {
  if () {
    .();
  } else {
    // file written successfully
  }
});

同步写入文件

🌐 Writing a file synchronously

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

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

const  = ('node:fs');

const  = 'Some content!';

try {
  .('/Users/joe/test.txt', );
  // file written successfully
} catch () {
  .();
}

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

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

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

async function () {
  try {
    const  = 'Some content!';
    await .('/Users/joe/test.txt', );
  } catch () {
    .();
  }
}

();

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

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

你可以通过指定一个标志来修改默认设置:

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

你可能会使用的标志是

🌐 The flags you'll likely use are

FlagDescriptionFile gets created if it doesn't exist
r+This flag opens the file for reading and writing
w+This flag opens the file for reading and writing and it also positions the stream at the beginning of the file
aThis flag opens the file for writing and it also positions the stream at the end of the file
a+This flag opens the file for reading and writing and it also positions the stream at the end of the file
  • 你可以在 fs 文档 中找到有关标志的更多信息。

向文件追加内容

🌐 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  = ('node:fs');

const  = 'Some content!';

.('file.log', ,  => {
  if () {
    .();
  } else {
    // done!
  }
});

使用 Promise 的示例

🌐 Example with Promises

这是一个 fsPromises.appendFile() 示例:

🌐 Here is a fsPromises.appendFile() example:

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

async function () {
  try {
    const  = 'Some content!';
    await .('/Users/joe/test.txt', );
  } catch () {
    .();
  }
}

();