Borislav Hadzhiev
Mon Mar 28 2022·3 min read
Photo by Max Ilienerwise
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.
// 👇️ 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.
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.
const arr = contents.split(/\r?\n/);
The forward slashes / /
mark the beginning and end of the regular expression.
\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.
example.txt
file located in the same directory. Make sure to also open your terminal in that same directory.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.
Alternatively, you could use the fsPromises
object to read a file
asynchronously.
To read a text file into an array:
fsPromises.readFile()
method to read the file's contents.String.split()
method to split the string into an array of
substrings.// 👇️ 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.
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.