fs.writeFile(file, data[, options], callback)
file
<string> | <Buffer> | <URL> | <integer> 文件名或文件描述符data
<string> | <Buffer> | <TypedArray> | <DataView>options
<Object> | <string>encoding
<string> | <null> 默认值:'utf8'
mode
<integer> 默认值:0o666
flag
<string> 请参阅对文件系统flags
的支持。 默认值:'w'
。
callback
<Function>err
<Error>
当 file
是文件名时,将数据异步地写入文件,如果文件已存在则替换该文件。
data
可以是字符串或缓冲区。
当 file
是文件描述符时,其行为类似于直接调用 fs.write()
(推荐)。
请参阅以下有关使用文件描述符的说明。
如果 data
是缓冲区,则忽略 encoding
选项。
const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
如果 options
是字符串,则它指定编码:
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
在同一个文件上多次使用 fs.writeFile()
而不等待回调是不安全的。
对于这种情况,建议使用 fs.createWriteStream()
。
file
<string> | <Buffer> | <URL> | <integer> filename or file descriptordata
<string> | <Buffer> | <TypedArray> | <DataView>options
<Object> | <string>encoding
<string> | <null> Default:'utf8'
mode
<integer> Default:0o666
flag
<string> See support of file systemflags
. Default:'w'
.
callback
<Function>err
<Error>
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.
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.
The encoding
option is ignored if data
is a buffer.
const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
If options
is a string, then it specifies the encoding:
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
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.