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

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 14, 2022, updated Aug 27, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-read-file-to-array

> A quick guide to learning 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](https://attacomsian.com/blog/javascript-string-split) into an array of substrings.

```javascript
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](https://attacomsian.com/blog/reading-a-file-line-by-line-in-nodejs) in Node.js.

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

```javascript
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!' ]
```
