fs.appendFileSync(path, data[, options])
path<string> | <Buffer> | <URL> | <number> 文件名或文件描述符data<string> | <Buffer>options<Object> | <string>
同步将数据追加到文件中,如果文件尚不存在则创建该文件。data 可以是字符串或 <Buffer>。
【Synchronously append data to a file, creating the file if it does not yet
exist. data can be a string or a <Buffer>.】
mode 选项只会影响新创建的文件。详情请参见 fs.open()。
【The mode option only affects the newly created file. See fs.open()
for more details.】
import { appendFileSync } from 'node:fs';
try {
appendFileSync('message.txt', 'data to append');
console.log('The "data to append" was appended to file!');
} catch (err) {
/* Handle the error */
} 如果 options 是字符串,则它指定了编码方式:
【If options is a string, then it specifies the encoding:】
import { appendFileSync } from 'node:fs';
appendFileSync('message.txt', 'data to append', 'utf8'); path 可以指定为已打开以便追加的数字文件描述符(使用 fs.open() 或 fs.openSync())。该文件描述符不会自动关闭。
【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 { openSync, closeSync, appendFileSync } from 'node:fs';
let fd;
try {
fd = openSync('message.txt', 'a');
appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
/* Handle the error */
} finally {
if (fd !== undefined)
closeSync(fd);
}