# Reading a text file into an Array in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

We can read a text file and return its content as an Array using node.js. We can use this array content to either process its lines or just for the sake of reading. We can use the 'fs' module to deal with the reading of file. The fs.readFile() and fs.readFileSync() methods are used for the reading files. We can also read large text files using this method.

Create a file with name – fileToArray.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node fileToArray.js

fileToArray.js

// Importing the fs module
let fs = require("fs")

// Intitializing the readFileLines with the file
.toString('UTF8')
.split('\n');

// Calling the readFiles function with file name

// Printing the response array
console.log(arr);

## Output

C:\home\node>> node fileToArray.js
[ 'Welcome to TutorialsPoint !',
'SIMPLY LEARNING', '' ]

Let's take a look at one more example.

// Importing the fs module
var fs = require("fs")

// Intitializing the readFileLines with filename
if(err) throw err;
var array = data.toString().split("\n");
for(i in array) {
// Printing the response array
console.log(array[i]);
}
});

## Output

C:\home\node>> node fileToArray.js
Welcome to TutorialsPoint !
SIMPLY LEARNING
Published on 20-May-2021 13:22:34