How to append in a text file in Node.js?

This blog describes how to append in a text file in Node.js.

To append to a text file in Node.js, you can use the fs.appendFile() function from the built-in fs (File System) module. This function appends data to a file, creating the file if it does not exist. Here’s how you can use it.

const fs = require('fs');

// Path to the file
const filePath = 'source.txt';

// Data to append
const dataToAppend = 'New data to append to the file.\n';

// Append data to the file
fs.appendFile(filePath, dataToAppend, (err) => {
    if (err) {
        console.error('Error appending to file:', err);
    console.log('Data appended to file successfully.');

The fs.appendFile() function takes three arguments.

  1. The path to the file.
  2. The data to append.
  3. A callback function that gets called after the operation completes. It receives an error object if an error occurred during the operation.

This code will append the specified data to the end of the file. If the file does not exist, it will be created.


Source Text File
Source Text File


Appending Text in a File
Appending Text in a File
Source Text File with Appended Text
Source Text File with Appended Text

Further Reading

JUnit Tutorial

Spring Framework Practice Problems and Their Solutions

30 MCQs on JUnit

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

100+ MCQs On Java Architecture

Java Practice Exercise



You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *