How to Read a Local Text File in JavaScript

To read a local text file in JavaScript, you can “use the FileReader object’s readAsText() method.” The readAsText() method accepts a file object and a callback function as arguments. The callback function will be called when the file has been read, receiving the file’s contents as a string.

The FileReader API is used to read a file asynchronously in collaboration with JavaScript event handling.

However, not all browsers have HTML 5 support, so it is essential to test the browser compatibility before using the File API.

Here are four inbuilt methods in the FileReader API to read local files:

Method 1: readAsArrayBuffer(blob)

  1. It reads the content of the specified Blob or File.
  2. When the read operation is finished, the load event is triggered, and the result attribute contains an ArrayBuffer representing the file’s data.

Method 2: readAsBinaryString(blob)

  1. It reads the content of the specified Blob or File.
  2. When the read operation is complete, the load event is triggered, and the result attribute contains a binary string representing the file’s data.

Method 3: readAsDataURL(blob)

  1. It reads the content of the specified Blob or File.
  2. When the read operation is finished, the load event is triggered, and the result attribute contains a data URL representing the file’s data as a base64 encoded string.

Method 4: readAsText(blob, [encoding])

  1. It reads the content of the specified Blob or File.
  2. When the read operation is finished, the load event is triggered, and the result attribute contains the file’s data as a text string.
  3. The optional encoding parameter can be specified (e.g., ‘UTF-8’, ‘ISO-8859-1’, etc.). If not provided, the default is ‘UTF-8’.

Example of Reading a Local Text File in JavaScript

We will read the data.txt file, which has the following content:

J Robert Oppenheimer and Albert Einstien
hello world
Jawaan

Write the below code in the HTML file.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="file" id="file-input">
  <script>
    const fileInput = document.getElementById('file-input');

    fileInput.addEventListener('change', (event) => {
    const file = fileInput.files[0];

    // Check if a file was selected
    if (!file) {
      return;
    }

    // Create a new FileReader object
    const reader = new FileReader();

    // This is called when the reading operation 
    // is successfully completed
    reader.onload = function () {
      // Display the file's contents
      console.log(reader.result);
    };

    // This is called when there's an error reading the file
    reader.onerror = function () {
      console.error('Error reading the file:', reader.error);
    };

    // Read the file
    reader.readAsText(file);
  });
 </script>
</body>

</html>

Output

Read a Local Text File in JavaScript

You can see that code created a new FileReader object and used it to read the file that the user selected.

The file’s contents will be stored in the text variable, and the console.log() statement will print the contents to the console.

Conclusion

In practice, you would use these methods depending on the type of file you’re reading and what you intend to do with its content.

For instance, the readAsDataURL() function is often used for image files you want to display directly in an <img> element, while the readAsText() function is commonly used for text files.

Related posts

How to Write a File in JavaScript

How to Read a JSON File in TypeScript

Leave a Comment