Last week, we learned how to read and write files in Node.js. The writeFile() method replaces a file if it already exists, though. Today, we'll learn how to append data to a file using the appendFile() method.

The appendFile() method

The fs.appendFile() method asynchronously appends data to a file, creating the file if it doesn't already exist. It accepts up to four arguments:

  1. The path to the file.
  2. The data to append to the file.
  3. An object literal of options or a string to specify the encoding.
  4. A callback function with an error parameter.

The following examples append the string 'Hello, World!' to the file hello_world.txt. If desired, we could prepend the string with the newline character ('\n') to ensure that the appended string appears on a new line.

Callback API

import { appendFile } from 'fs';

const file = 'hello_world.txt';
const data = 'Hello, World!';

appendFile(file, data, 'utf8', error => {
if (error) {
throw error;
} else {
console.log(`Appended string "${data}" to ${file}.`);
}
});

Promises API

The fsPromises.appendFile() method returns a promise that fulfills with undefined upon success. This means we don't need to specify a parameter for our callback to the then() method.

import { appendFile } from 'fs/promises';

const file = 'hello_world.txt';
const data = 'Hello, World!';

appendFile(file, data, 'utf8')
.then(() => console.log(`Appended string "${data}" to ${file}.`))
.catch(console.error);

All the code from this post is available as a Gist.