Read a text file into an Array using Node.js

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
3 min

banner

# Read a text file into an Array asynchronously in Node.js

To read a text file into an array:

  1. Use the fsPromises.readFile() method to read the file's contents.
  2. Await the promise that the method returns.
  3. Use the String.split() method to split the string into an array of substrings.
index.js
// ๐Ÿ‘‡๏ธ if using ES6 Imports uncomment line below // import {readFileSync, promises as fsPromises} from 'fs'; const {promises: fsPromises} = require('fs'); // โœ… read file ASYNCHRONOUSLY async function asyncReadFile(filename) { try { const contents = await fsPromises.readFile(filename, 'utf-8'); const arr = contents.split(/\r?\n/); console.log(arr); // ๐Ÿ‘‰๏ธ ['One', 'Two', 'Three', 'Four'] return arr; } catch (err) { console.log(err); } } asyncReadFile('./example.txt');
The code for this article is available on GitHub

Note: if you use the ES6 import/export syntax, use the following import statement instead.

index.js
import {readFileSync, promises as fsPromises} from 'fs';
The code snippet assumes that there is an example.txt file located in the same directory. Make sure to also open your terminal in that same directory.
example.txt
One Two Three Four

read text file into array asynchronously

The code for this article is available on GitHub

The directory structure in the example assumes that the index.js file and the example.txt file are located in the same folder and our terminal is also in that folder.

read file into array

The fsPromises.readFile() method asynchronously reads the contents of the provided file.

If you don't provide a value for the encoding parameter, the method returns a buffer, otherwise, a string is returned.

The method returns a promise that resolves with the contents of the file, so we either have to await it or use the .then() method on it to get the resolved string.

We used the String.split() method to split the contents on each newline character.

We passed a regular expression to the split() method.

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

The forward slashes / / mark the beginning and end of the regular expression.

We want to replace both \r and \n because the line breaks vary depending on the operating system.

For example, Windows uses \r\n as an end-of-line character, whereas \n is the default in Unix.

The question mark ? matches the preceding item (\r) 0 or 1 times. In other words, the \r might or might not be there.

The split() method returns an array containing the substrings (each line) as elements.

Alternatively, you can read the file synchronously.

# Read a text file into an Array synchronously using Node.js

Use the fs.readFileSync method to read a text file into an array synchronously.

The method will return the contents of the file, which we can split on each newline character to get an array of strings.

index.js
// ๐Ÿ‘‡๏ธ if using ES6 Imports uncomment line below // import {readFileSync, promises as fsPromises} from 'fs'; const {readFileSync} = require('fs'); // โœ… read file SYNCHRONOUSLY function syncReadFile(filename) { const contents = readFileSync(filename, 'utf-8'); const arr = contents.split(/\r?\n/); console.log(arr); // ๐Ÿ‘‰๏ธ ['One', 'Two', 'Three', 'Four'] return arr; } syncReadFile('./example.txt');
The code for this article is available on GitHub

Note: if you use the ES6 import/export syntax, use the following import statement instead.

index.js
import {readFileSync, promises as fsPromises} from 'fs';

read text file into array synchronously

The function from the first example reads the contents of a file synchronously.

The fs.readFileSync() method takes the path to the file as the first parameter and the encoding as the second.

The method returns the contents of the provided path.

If you omit the encoding parameter, the function will return a buffer, otherwise, a string is returned.

# Read a text file into an Array asynchronously using .then()

The first code sample reads a text file into an array asynchronously using async/await.

If you prefer using the .then() and .catch() syntax when handling Promises, use the following code snippet instead.

index.js
// ๐Ÿ‘‡๏ธ if using ES6 Imports uncomment line below // import {readFileSync, promises as fsPromises} from 'fs'; const {promises: fsPromises} = require('fs'); // โœ… read file ASYNCHRONOUSLY function asyncReadFile(filename) { return fsPromises .readFile(filename, 'utf-8') .then(contents => { const arr = contents.split(/\r?\n/); console.log(arr); // ๐Ÿ‘‰๏ธ ['One', 'Two', 'Three', 'Four'] return arr; }) .catch(err => { console.log(err); }); } asyncReadFile('./example.txt');

read text file into array asynchronously using then

The code for this article is available on GitHub

The code sample achieves the same result but makes use of the .then() and .catch() syntax instead of a try/except block using async/await.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev