Read a text file into an Array using JavaScript

avatar

Borislav Hadzhiev

Mon Mar 28 20223 min read

Read a text file into an Array using JavaScript #

Use the fs.readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8').split('\n'). 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, promises: fsPromises} = 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'); // -------------------------------------------------------------- // ✅ 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 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.

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 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 be there, or it might not be there.

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

The code snippet above 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

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

Alternatively, you could use the fsPromises object to read a file asynchronously.

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 {readFileSync, 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 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 fulfills with the contents of the file, so we have to await it or use the .then() method on it to get the resolved string.

To get an array of the file's contents, we have to call the split() method on the resolved string.

Use the search field on my Home Page to filter through my more than 1,000 articles.