To read a text file into an array in Node.js:

  1. Use the fsPromises.readFile() to read the file contents into a string.
  2. Await until the promise returned by the above method has been resolved.
  3. Use the split() method to split the string into an array of substrings.
const fsPromises = require('fs/promises')

const readFileAsync = async () => {
  try {
    const contents = await fsPromises.readFile('file.txt', 'utf-8')

    const arr = contents.split(/\r?\n/)

    console.log(arr)
    // [ 'this', 'is', 'an', 'example two two', 'text!' ]
  } catch (err) {
    console.error(err)
  }
}

readFileAsync()

The fsPromises.readFile() method takes the path to the file as the first parameter and the encoding as the second. It asynchronously reads the contents of the given file.

If you skip the encoding parameter, fsPromises.readFile() will return a buffer. Otherwise, a string is returned.

We used the String.split() method to split the file contents on each newline character. We did the same for reading a file line by line in Node.js.

In case you need to read the file contents synchronously, use the fs.readFileSync() method instead:

const fs = require('fs')

const contents = fs.readFileSync('file.txt', 'utf-8')

const arr = contents.split(/\r?\n/)

console.log(arr)
// [ 'this', 'is', 'an', 'example two two', 'text!' ]

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.