JavaScript

How to read a local text file using JavaScript?

In Javascript, multiple packages and APIs are available that allow the user to read data from a locally placed file. Two of the most famous of these libraries are

  1. File System Package: Allows javascript programs to read files from the system
  2. FileReaderWeb API: Allows the work with files from an HTML webpage.

As you can see, both work differently; one works for an HTML webpage and the other for local Javascript programs.

File System Package for reading files on your desktop

The file system package comes with the default node environment for locally hosted JavaScript programs. However, you still need to include the File system package into your javascript code using the required keyword. After that, the function readFile() included in this package allows you to read data from a file.

Syntax of readFile() method
The syntax of the readFile() method is given as:

FileSystemVar.readFile( PathToTheFile, Options, CallbackFunction);

The details of this syntax are as:

  • FileSystamVar: This is the variable that has been set equal require filesystem package
  • PathToTheFile: This is the path to the file that you want to read
  • Options: These are the optional options that can filter encoding and other attributes of the file
  • CallbackFunction: A callback function that will be executed upon a successful read of the file

Example 1: Reading a file with File System Package

Start off by creating a new text file on your computer and place some text inside it like

After that, head inside your javascript file and include the file system package using the require keyword:

const fs = require("fs");

Then use the following lines:

fs.readFile("demo.txt", (err, data) => {
  if (err) throw err;

  console.log(data.toString());
});

The following steps are being performed in the code mentioned above:

  • Read the file “demo.txt
  • If there is an error, then throw that error message onto the terminal
  • In case of no error, store the data read from the file in the data variable
  • Print the content of the data variable after converting it to string using the toString() method

Upon execution of the code, you will observe the following output on your terminal:

The data from the file has been printed onto the terminal.

FileReader Web API for reading files on an HTML webpage

File reader API only works with HTML web pages, and one of the restrictions of this API is that it works on the files that have been read by <input type= “file”> tag. It has multiple functions that allow the user to read the file in different encodings.

Example 2: Reading a local text file from an HTML webpage

Start by setting up an HTML webpage, for that use the following lines:

<center>
      <input type="file" name="inputFileToRead" id="inputFileToRead" />
      <br />
</center>

You will get the following webpage on your browser:

After that, head over to the javascript file and write down the following lines of code:

document.getElementById("inputFileToRead")
  .addEventListener("change", function () {
    var fr = new FileReader();
    fr.readAsText(this.files[0]);
    fr.onload = function () {
      console.log(fr.result);
    };  
  });

The following steps are being performed in the code mentioned above:

  • An action listener is being applied on your <input> with the id “inputFileToRead
  • Then a object of file reader (fr) has been created using the FileReader() constructor
  • Then the first file on the <input> is being read as a text using the fr variable
  • Upon successful read of the file that data is being printed onto the console

To demonstrate this, select the same file that was selected in the first example and you will get the following result on the console of your browser:

The result shows that the file has been successfully read by the HTML webpage.

Conclusion

To read a locally placed text file, we have two options: to load the file in HTML or to read that file in your desktop javascript program. For this, you have File Reader Web API for web pages and a file system package for desktop JavaScript. Essentially, both of these perform the same operation: reading a text file. In this tutorial, you have used the readFile() function from the File system package and readFileAsText() from the File Reader Web API.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.