. Advertisement .
..3..
. Advertisement .
..4..
JavaScript is a versatile programming language designed to add interactivity to the website. Nowadays, almost every website you come across has interactive, which makes it user-friendly. Be it games, animations, interactive forms, or dynamic styling, everything is possible because of JavaScript.
When it comes to JavaScript, beginners have often seen asked how to read a text file into an array using JavaScript as they encounter errors.
How to read a text file using JavaScript?
JavaScript allows us to read a file and return the content as an array with the help of node.js. Array content can either be read or processed the lines. The use of the ‘fs’ module helps us read a file. Two methods are used to read files; fs.readFileSync() and fs.readFile(). Even large files can be read using this method. Examples are discussed below
Let’s go through the code
Using fs.readFile()
This method is known as the simplest method to read a file. Fs.readFile() method read the complete file into buffer.
Syntax
fs.readFile( filename, encoding, callback_function )
As you can see, this method accepts three parameters. Where filename is the name of the file that you want to read, even an entire file location can be the name if stored at another location. Encoding consists of the file’s encoding and ‘utf8’ is the default value. Whereas the callback function is to call once the reading of the file is done.
Code
const fs = require('fs');
fs.readFile('/Users/joe/test.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
Using fs.readFileSync()
This method is used to read the text file synchronously, which makes the code execution stops until the fs.readFileSync() method is finished.
Syntax
fs.readFileSync( path, options )
Where path is the path of the text file that can be in URL type or file descriptor. In the case both are in the same folder, the filename can be given in quotes. Option is the optional parameter that includes the flag and encoding ( contains data specifications).
Using String split() Method
It is used to split the string into an array. With the use of a specified separator passed in the argument, strings are separating into substrings.
Syntax: str.split(separator, limit)
Example:
<script>
// JavaScript Program to illustrate split() function
function func() {
//Original string
var str = 'ITtutoria and ITprospt'
var array = str.split("and");
document.write(array);
}
func();
</script>
Output
ITtutoria, ITprospt
Conclusion
Here, you get to know how to read a text file into an array using JavaScript in a few ways. With that, I hope you find it easy to keep going with the JavaScript array code the next time you try.
Don’t hesitate to comment below if you need assistance!
Leave a comment