How to append in a text file in Node.js? – Programmingempire – The Global Tofay

How to append in a text file in Node.js? - Programmingempire - The Global Tofay Global Today

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);
        return;
    }
    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.txt

Source Text File
Source Text File

Output

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

  • Angular
  • ASP.NET
  • C
  • C#
  • C++
  • CSS
  • Dot Net Framework
  • HTML
  • IoT
  • Java
  • JavaScript
  • Kotlin
  • PHP
  • Power Bi
  • Python
  • Scratch 3.0
  • TypeScript
  • VB.NET
programmingempire

Princites

#append #text #file #Node.js #Programmingempire

Leave a Reply

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