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.

Example (Using readFileSync())

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
const readFileLines = filename =>
   fs.readFileSync(filename)
   .toString('UTF8')
   .split('\n');

// Calling the readFiles function with file name
let arr = readFileLines('tutorialsPoint.txt');

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

Output

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

Example (Using async readFile())

Let's take a look at one more example.

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

// Intitializing the readFileLines with filename
fs.readFile('tutorialsPoint.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

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