Reading a text file into an Array in Node.js


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('
'); // Calling the readFiles function with file name let arr = readFileLines('tutorialsPoint.txt'); // Printing the response array console.log(arr);

Output

C:\home
ode>> 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("
");    for(i in array) {       // Printing the response array       console.log(array[i]);    } });

Output

C:\home
ode>> node fileToArray.js Welcome to TutorialsPoint ! SIMPLY LEARNING

Updated on: 20-May-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements