fs.appendFile(path, data[, options], callback)
path<string> | <Buffer> | <URL> | <number> 文件名或文件描述符data<string> | <Buffer>options<Object> | <string>encoding<string> | <null> 默认值:'utf8'mode<integer> 默认值:0o666flag<string> 请参阅对文件系统flags的支持。 默认值:'a'。
callback<Function>err<Error>
异步地将数据追加到文件,如果该文件尚不存在,则创建该文件。
data 可以是字符串或 <Buffer>。
mode 选项仅影响新创建的文件。
有关详细信息,请参阅 fs.open()。
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});如果 options 是字符串,则它指定编码:
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);可以将 path 指定为已打开用于追加(使用 fs.open() 或 fs.openSync())的数字文件描述符。
文件描述符不会自动关闭。
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});path<string> | <Buffer> | <URL> | <number> filename or file descriptordata<string> | <Buffer>options<Object> | <string>encoding<string> | <null> Default:'utf8'mode<integer> Default:0o666flag<string> See support of file systemflags. Default:'a'.
callback<Function>err<Error>
Asynchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a <Buffer>.
The mode option only affects the newly created file. See fs.open()
for more details.
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});If options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);The path may be specified as a numeric file descriptor that has been opened
for appending (using fs.open() or fs.openSync()). The file descriptor will
not be closed automatically.
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});