fs.writeFile(file, data[, options], callback)


file 是文件名时,会异步将数据写入该文件,如果文件已存在则会替换它。data 可以是字符串或缓冲区。

【When file is a filename, asynchronously writes data to the file, replacing the file if it already exists. data can be a string or a buffer.】

file 是一个文件描述符时,其行为类似于直接调用 fs.write()(这是推荐的做法)。有关使用文件描述符的说明,请参见下面的备注。

【When file is a file descriptor, the behavior is similar to calling fs.write() directly (which is recommended). See the notes below on using a file descriptor.】

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

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

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

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

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

const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
}); 

如果 options 是字符串,则它指定了编码方式:

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

import { writeFile } from 'node:fs';

writeFile('message.txt', 'Hello Node.js', 'utf8', callback); 

在未等待回调的情况下多次使用 fs.writeFile() 写入同一个文件是不安全的。对于这种情况,推荐使用 fs.createWriteStream()

【It is unsafe to use fs.writeFile() multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream() is recommended.】

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

【Similarly to fs.readFile - fs.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().】

可以使用 <AbortSignal> 来取消 fs.writeFile()。取消是“尽力而为”的,因此仍有可能写入部分数据。

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

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

const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
  // When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort(); 

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

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