How to read a text file into an array with each line an item in the array?

Sometimes, we want to read a text file into an array with each line an item in the array.

In this article, we’ll look at how to read a text file into an array with each line an item in the array.

How to read a text file into an array with each line an item in the array?

To read a text file into an array with each line an item in the array, we can use the readFileSync or readFile method.

For instance, we write

const fs = require('fs');

const array = fs.readFileSync('file.txt').toString().split("n");
for (const a of array) {
  console.log(a);
}

to call fs.readFileSync to read 'file.txt' synchronously.

Then we call toString to return the read file as a string.

And then we split the string into an array with each line as an item with split.

Then we loop through each array entry with the for-of loop.

We call readFile to read the file asynchronously.

To use it, we write

const fs = require('fs');

fs.readFile('file.txt', (err, data) => {
  if (err) {
    throw err;
  }
  
  const array = data.toString().split("n");
  for (const a of array) {
    console.log(a);
  }
});

to call readFile to read 'file.txt'.

The callback is run when the file is read.

And we convert the file to a string, split the lines, and loop through them the same way.

Conclusion

To read a text file into an array with each line an item in the array, we can use the readFileSync or readFile method.