跳到内容

使用 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.

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

你可能会使用的标志是

🌐 The flags you'll likely use are

标志描述如果文件不存在则创建文件
r+该标志用于读取写入文件
w+该标志用于读取写入文件,并将流定位到文件的开头
a该标志用于写入文件,并将流定位到文件的末尾
a+该标志用于读取写入文件,并将流定位到文件的末尾
  • 你可以在 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 () {
    .();
  }
}

();