How to Append Text or Lines to a Text File in Node.js?

31-Aug-2022

.

Admin

How to Append Text or Lines to a Text File in Node.js?

Hi friends,

This article will provide an example of how to append text in text file nodejs. Here you will learn how to add a string to text file node js. This article goes into detail on node.js append text to a text file. I’m going to show you about node js edit text file.

In this tutorial, we learn to append text or lines to a text file in nodejs using Node FS (File System) built-in module. Node.js example programs that use appendFile() function are provided. So, let's follow a few steps to create an example of node js append text or lines exists file.

So, let's start follwing example with output:

Step 1: Create Node.js Project


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Step 2: Update index.js File

index.js

// include node fs module

fs = require('fs');

// appendFile function append new line existing file

fs.appendFile('readme.txt','New data to append', function (err) {

// print output

console.log('Saved!');

});

Output:

open your readme.txt file with following text.

Hello welcome to Nicesnippets.com

New data to append

I hope it can help you...

#Node JS