How to read a text file into an array using Node.js

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.