How to append a file in Node.js

Problem statement

Implement an fs.appendFile() function that asynchronously appends data to the end of the test.txt file.

The fs module

The fs module is a built-in global Node.js module that exposes an API to access, manipulate, and interact with the file system.

Syntax

fs.appendFile(path, data)

Parameters

  • path: This is a file path.
  • data: This is the data to be written to the file.

Example

Let’s look at the code below:

index.js
test.txt
const fs = require("fs").promises;
const appendFile = async (path, data) => {
try {
await fs.appendFile(path, data);
} catch (error) {
console.error(error);
}
};
appendFile("./test.txt", "appending another hello world");

Explanation

  • Line 1: We load the fs module to read a file. The module system uses the require function to load in a module and access its contents. We use promise objects for async/await keywords instead of callbacks to handle asynchronicity.

  • Line 2: We store an async path where the file is located and the data that we need to append in the text file.

  • Line 3–8: We use a try and catch and append the data in the file.

  • Line 9: We set a path of a file and data as a parameter in the appendFile function.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved