Open In App

How to read a local text file using JavaScript?

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Imagine your web page wants to interact with files on the user’s computer. HTML 5 provides a handy tool called the File API to make this possible. The File API allows interaction with single, multiple as well and BLOB files.

The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling. However, all the browsers do not have HTML 5 support so it is important to test the browser compatibility before using the File API.

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

  • FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file’s data.
  • FileReader.readAsBinaryString(): Reads the contents of the specified input file. The result attribute contains the raw binary data from the file as a string.
  • FileReader.readAsDataURL(): Reads the contents of the specified input file. The result attribute contains a URL representing the file’s data.
  • FileReader.readAsText(): Reads the contents of the specified input file. The result attribute contains the contents of the file as a text string. This method can take the encoding version as the second argument(if required). The default encoding is UTF-8.

Different Examples to read Local Text File

Example 1: In this example, we are using the FileReader.readAsText() method to read the local file.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Read Text File</title>
</head>

<body>
    <input type="file" name="inputfile" id="inputfile">
    <br>

    <pre id="output"></pre>

    <script type="text/javascript">
        document.getElementById('inputfile')
            .addEventListener('change', function () {

                let fr = new FileReader();
                fr.onload = function () {
                    document.getElementById('output')
                        .textContent = fr.result;
                }

                fr.readAsText(this.files[0]);
            })
    </script>
</body>

</html>

Example 2: In this example, we are using the FileReader.readAsBinaryString()method to read the local file.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Read Text File</title>
</head>

<body>
    <input type="file" name="inputfile" id="inputfile">
    <br>

    <pre id="output"></pre>

    <script type="text/javascript">
        document.getElementById('inputfile')
            .addEventListener('change', function () {

                let fr = new FileReader();
                fr.onload = function () {
                    document.getElementById('output')
                        .textContent = fr.result;
                }

                fr.readAsBinaryString(this.files[0]);
            })
    </script>
</body>

</html>

Output:

sample15

Output


JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Similar Reads

Javascript | Program to read text File
Given a text file, write a JavaScript program to extract the contents of that file. There is a built-in Module or in-built library in NodeJs that handles all the reading operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for reading operations is written. Import fs-module in the program and use functio
2 min read
Create a Read More Read Less Button using HTML CSS and JavaScript
The "read more - read less" button is a commonly used feature that enhances user experience by providing a convenient way to reveal or hide content. The article covers two distinct approaches, including Display Inline and Display Block. Table of Content Using Display InlineUsing Display BlockUsing Display InlineCreate a separate HTML, CSS, and Java
4 min read
Explain about Read and Write of a file using JavaScript
On the client side, you can't read or write files in JavaScript browsers. The fs module in Node.js may be used to accomplish this on the server-side. It has methods for reading and writing files on the file system that are both synchronous and asynchronous. Let's demonstrate some examples of reading and writing files with the node.js fs module. The
3 min read
Read XML file and print the details as tabular data by using JavaScript
To read the XML file and print the details of an XML file in a Tabular form by using JavaScript. We need to create an XML file with the data we want to print. XML stands for Extensible Markup LanguageĀ· It is a markup language very similar to HTML. The main purpose of the XML file is to store and transport the data. Creating an XML file is very simp
4 min read
Read JSON File using JavaScript
JSON stands for JavaScript Object Notation. It's a way of organizing data in a script file using text, making it easy to store and share data. Reading JSON files, whether they're stored locally or on a server, is crucial for web applications. In this tutorial, we'll cover three methods for reading JSON files in JavaScript, which can be really helpf
4 min read
How to read data from a file stored in XAMPP webserver using PHP ?
We have given a file stored on XAMPP server and the task is to read the file from server and display the file content on the screen using PHP. We use some PHP functions to solve this problem. File: A file is set of data stored in a disk in different formats. For example - .txt, .exe, .pdf etc fopen() function: The fopen() function in PHP is an inbu
2 min read
How to read PDF file using PHP ?
In this article, we will learn how you can show/read PDF file contents on a browser using PHP. We have to include an external PHP file named "class.pdf2text.php". Include it in the required web page using PHP. Create an HTML form, in which we can choose a PDF file from your computer and also check whether its file extension is PDF or not. Approach:
3 min read
How to Read a File Line by Line using Node.js ?
The ability to Read a File Line by Line allows us to read large files without entirely storing them in memory. It is useful in saving resources and improving the efficiency of the application. It allows us to look for the information that is required and once the relevant information is found, we can stop the search process and can prevent unwanted
3 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and text-based format for exchanging data between diff
3 min read
Local File Inclusion (LFI)
A File Inclusion Vulnerability is a type of Vulnerability commonly found in PHP based websites and it is used to affect the web applications. This issue generally occurs when an application is trying to get some information from a particular server where the inputs for getting a particular file location are not treated as a trusted source. It gener
4 min read