. Advertisement .
..3..
. Advertisement .
..4..
JavaScript is a programming language or scripting that enables you to execute complex attributes on web pages. Every time a web page does more than only sit there and show static information for you to see. It shows timely content updates, animated 2D/3D graphics, interactive maps, scrolling video jukeboxes, etc. “How to read a text file into an array using JavaScript” is a fairly common problem that any programmer will face. So, what are our alternatives? Everything will be made clear to you in this article. Read on it.
What can we do to read a text file into an array using JavaScript?
Let’s follow these steps to read a text file into an array using JavaScript:
- To read the contents of the file, use the fsPromises.readFile() method.
- Await the method’s promised return.
- Split the string into an array of substrings using the String.split() method.
Step 1: Utilize the fsPromises.readFile() or fs.readFileSync() method
1. Utilize the fsPromises.readFile()
Syntax:
fsPromises.readFile( path, options )
Look at the following example to understand more about this method:
// 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 array = contents.split(/\r?\n/);
console.log(array); // ['One', 'Two', 'Three', 'Four']
return array;
} catch (err) {
console.log(err);
}
}
asyncReadFile('./ittutoria.txt');
The specified file’s contents are read asynchronously via the fsPromises.readFile() method. The method returns a buffer if the encoding option is left empty; a string is returned otherwise.
2. Utilize the fs.readFileSync()
Syntax:
fs.readFileSync( path, options )
Additionally, you can utilize the fs.readFileSync() method to read a text file into an array in JavaScript is not a bad solution, for example, const contents = readFileSync(filename, 'utf-8').split('\n')
. This approach will return the file’s contents, which you can divide on each newline character to obtain 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 array = contents.split(/\r?\n/);
console.log(array); // ['One', 'Two', 'Three', 'Four']
return array;
}
syncReadFile('./ittutoria.txt');
// --------------------------------------------------------------
// read file ASYNCHRONOUSLY
async function asyncReadFile(filename) {
try {
const contents = await fsPromises.readFile(filename, 'utf-8');
const array = contents.split(/\r?\n/);
console.log(array); // ['One', 'Two', 'Three', 'Four']
return array;
} catch (err) {
console.log(err);
}
}
asyncReadFile('./ittutoria.txt');
The first example’s code synchronously reads a file’s content. The first parameter to the fs.readFileSync method is the file path, and the second is the encoding. The method returns the information found on the given path. The function returns a buffer if the encoding option is omitted; a string is returned otherwise.
Step 2: Await the method’s promised return
To obtain the resolved string, you must either await the function’s return value or use the.then() method on the promise it creates, which fulfills the file’s contents. Then, you must use the split() method on the resolved string to obtain an array containing the file’s contents.
Step 3: Utilize the String.split() method
Additionally, you divide the text on each newline character using the String.split method.
The split() method accepts a regular expression as an argument.
const arr = contents.split(/\r?\n/);
The regular expressions’ start and finish are indicated by forward slashes / /
marks. Since line breaks differ depending on the operating system, you want to replace both r and n. For instance, the default end-of-line character in Unix is n
, but Windows uses \r\n
. The question mark (?) corresponds to the previous item (r) either 0 or 1 times. To put it another way, the r may or may not be present. The substrings (each line) are returned as elements of the array that the split() method returns.
One
Two
Three
Four
The example’s directory structure presupposes that your terminal is in the same folder as the ittutoria.txt and the index.js and ittutoria.txt files.
[ 'one', 'two', 'three', 'four']
[ 'one', 'two', 'three', 'four']
Conclusion
The solutions presented above are the best solutions for “How to read a text file into an array using JavaScript”. We hope this blog has helped clear the air around how to do it. If you have more questions about this topic, please leave a comment below. Thank you for reading, we are always excited when one of our posts can provide useful information on a topic like this!
Read more
→ How To Convert a Date string to ISO format using JavaScript
Leave a comment