fs.appendFileSync(path, data[, options])


同步地将数据追加到文件,如果文件尚不存在则创建该文件。 data 可以是字符串或 Buffer

try {
  fs.appendFileSync('message.txt', '追加的数据');
  console.log('数据已追加到文件');
} catch (err) {
  /* 处理错误 */
}

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

fs.appendFileSync('message.txt', '追加的数据', 'utf8');

path 可以指定为已打开用于追加(使用 fs.open()fs.openSync())的数字型文件描述符。 文件描述符不会自动关闭。

let fd;

try {
  fd = fs.openSync('message.txt', 'a');
  fs.appendFileSync(fd, '追加的数据', 'utf8');
} catch (err) {
  /* 处理错误 */
} finally {
  if (fd !== undefined)
    fs.closeSync(fd);
}

Synchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.

try {
  fs.appendFileSync('message.txt', 'data to append');
  console.log('The "data to append" was appended to file!');
} catch (err) {
  /* Handle the error */
}

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

fs.appendFileSync('message.txt', 'data to append', 'utf8');

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.

let fd;

try {
  fd = fs.openSync('message.txt', 'a');
  fs.appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
  /* Handle the error */
} finally {
  if (fd !== undefined)
    fs.closeSync(fd);
}