How to Read a Text File into an Array in Node.js?

Aug 30, 2022

.

Admin

How to Read a Text File into an Array in Node.js?

Hi friends,

This tutorial will provide an example of how to read a text file into an array in node.js. you'll learn to read a text file into an array in node js. I would like to share with you read a text file into an array in nodejs. This article goes in detailed on read a text file into an array in nodejs. Let's see bellow example nodejs read a text file into an array.

We can read a text file and return its content as an Array using node js. We can use the 'fs' module to deal with the reading of files. The fs.readFile() and fs.readFileSync() methods are used for the reading files.

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

// Importing the fs module

fs = require("fs")

// Intitializing the readFileLines with filename

fs.readFile('readme.txt', function(err, data) {

if(err) throw err;

var array = data.toString().split("\n");

for(i in array) {

// Printing the response array

console.log(array[i]);

}

});

Output:

It will create readme.txt file with following text.

Hello welcome to Nicesnippets.com

I hope it can help you...

#Node JS