fsPromises.writeFile(file, data[, options])
-
file
<string> | <Buffer> | <URL> | <FileHandle> 文件名或FileHandle
¥
file
<string> | <Buffer> | <URL> | <FileHandle> filename orFileHandle
-
data
<string> | <Buffer> | <TypedArray> | <DataView> | <AsyncIterable> | <Iterable> | <Stream> -
-
mode
<integer> 默认值:0o666
¥
mode
<integer> Default:0o666
-
flag
<string> 参见 支持文件系统flags
。默认值:'w'
。¥
flag
<string> See support of file systemflags
. Default:'w'
. -
signal
<AbortSignal> 允许中止正在进行的 writeFile¥
signal
<AbortSignal> allows aborting an in-progress writeFile
-
返回:<Promise> 成功时将使用
undefined
履行。¥Returns: <Promise> Fulfills with
undefined
upon success.
异步地将数据写入文件,如果文件已经存在,则替换该文件。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.
在同一个文件上多次使用 fsPromises.writeFile()
而不等待 promise 被解决是不安全的。
¥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.