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


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

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

如果 options 是字符串,则它指定编码。

mode 选项仅影响新创建的文件。 有关详细信息,请参阅 fs.open()

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

在同一个文件上多次使用 fsPromises.writeFile() 而不等待 promise 被解决是不安全的。

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

可以使用 <AbortSignal> 取消 fsPromises.writeFile()。 取消是"尽力而为"的,并且可能仍会写入一些数据。

import { writeFile } from 'fs/promises';

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

  // 在 promise 达成之前中止请求。
  controller.abort();

  await promise;
} catch (err) {
  // 当请求中止时 - err 是 AbortError
  console.error(err);
}

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

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

The encoding option is ignored if data is a buffer.

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

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

Any specified <FileHandle> has to support writing.

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

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().

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 'fs/promises';

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);
}

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