fsPromises.writeFile(file, data[, options])


异步将数据写入文件,如果文件已存在则替换。data 可以是字符串、缓冲区、<AsyncIterable><Iterable> 对象。

【Asynchronously writes data to a file, replacing the file if it already exists. data can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.】

如果 data 是缓冲区,则会忽略 encoding 选项。

【The encoding option is ignored if data is a buffer.】

如果 options 是字符串,那么它指定了编码。

【If options is a string, then it specifies the encoding.】

mode 选项只会影响新创建的文件。详情请参见 fs.open()

【The mode option only affects the newly created file. See fs.open() for more details.】

任何指定的 <FileHandle> 都必须支持写入。

【Any specified <FileHandle> has to support writing.】

在不等待 Promise 完成的情况下,多次使用 fsPromises.writeFile() 写入同一个文件是不安全的。

【It is unsafe to use fsPromises.writeFile() multiple times on the same file without waiting for the promise to be settled.】

fsPromises.readFile 类似,fsPromises.writeFile 是一个便捷方法,它内部执行多次 write 调用来写入传入的缓冲区。对于对性能敏感的代码,建议考虑使用 fs.createWriteStream()filehandle.createWriteStream()

【Similarly to fsPromises.readFile - fsPromises.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using fs.createWriteStream() or filehandle.createWriteStream().】

可以使用 <AbortSignal> 来取消 fsPromises.writeFile()。取消是“尽最大努力”的,有些数据仍可能会被写入。

【It is possible to use an <AbortSignal> to cancel an fsPromises.writeFile(). Cancelation is "best effort", and some amount of data is likely still to be written.】

import { writeFile } from 'node:fs/promises';
import { Buffer } from 'node:buffer';

try {
  const controller = new AbortController();
  const { signal } = controller;
  const data = new Uint8Array(Buffer.from('Hello Node.js'));
  const promise = writeFile('message.txt', data, { signal });

  // Abort the request before the promise settles.
  controller.abort();

  await promise;
} catch (err) {
  // When a request is aborted - err is an AbortError
  console.error(err);
} 

中止正在进行的请求并不会中止单个操作系统请求,而是中止 fs.writeFile 执行的内部缓冲操作。

【Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.writeFile performs.】