How to read a local text file using JavaScript?
Last Updated :
21 Jun, 2025
JavaScript can read local files using the File API, which is supported by most modern browsers. The File API allows JavaScript to read the contents of files chosen by the user, typically through an HTML file input element.
- The File object represents a file (like a text file or image) selected by the user.
- The FileReader API allows JavaScript to read the contents of the file.
To start reading a file, the user first needs to select it. This can be achieved using a simple file input:
<input type="file" id="fileInput">
- <input>: This is the HTML tag used to create various types of input elements in a form.
- type="file": This attribute specifies that the input field will allow the user to select files from their local system.
- id="fileInput": This attribute assigns an ID to the input element. The ID is useful for referencing the element in JavaScript or CSS.
Methods of FileReader for Reading Files
Below are some common methods of FileReader for Reading Files:
1. FileReader.readAsArrayBuffer() Method
The FileReader.readAsArrayBuffer() method is part of the FileReader API in JavaScript and allows reading the contents of a file as a binary array buffer.
HTML
<html>
<head>
<meta charset="UTF-8">
<title>Read File as ArrayBuffer</title>
</head>
<body>
<input type="file" id="fileInput">
<div id="fileContents"></div>
<script>
document
.getElementById('fileInput')
.addEventListener('change', function (event) {
let file = event.target.files[0];
let reader = new FileReader();
reader.onload = function (event) {
let arrayBuffer = event.target.result;
let array = new Uint8Array(arrayBuffer);
let fileSize = arrayBuffer.byteLength;
let bytes = [];
for (let i = 0; i < Math.min(20, fileSize); i++) {
bytes.push(array[i]);
}
document
.getElementById('fileContents')
.textContent =
'First 20 bytes of file as ArrayBuffer: '
+ bytes.join(', ');
console.log('ArrayBuffer:', arrayBuffer);
};
reader.readAsArrayBuffer(file);
});
</script>
</body>
</html>
Output:
How to read a local text file using JavaScript?In this example
- An <input> field allows the user to select a file, and a <div> is used to display the first 20 bytes.
- When a file is selected, a FileReader reads the file as an ArrayBuffer.
- The first 20 bytes of the file are displayed in the <div>.
- The Uint8Array is used to handle the binary data and extract the bytes.
2. FileReader.readAsText()
The FileReader.readAsText() method is a part of the FileReader API in JavaScript. It allows reading the contents of a file as a text string, which is especially useful for handling text files such as .txt, .csv, .json, and similar file formats.
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>
Output:
Read a local text file using JavaScriptIn this example
- An <input> field (type="file") allows the user to select a file.
- A <pre> tag with id="output" is used to display the contents of the file.
- Event Listener: When the user selects a file, the change event is triggered.
- FileReader: A FileReader object (fr) is used to read the file.
- onload Event: Once the file is successfully read, its contents are displayed in the <pre> tag by setting textContent to the result of the FileReader.
- fr.readAsText(this.files[0]): Reads the selected file as a text string.
3. FileReader.readAsDataURL()
The FileReader.readAsDataURL() method is part of the FileReader API in JavaScript and is used to read the contents of a file and return it as a data URL. This method is especially useful when working with binary files like images, audio files, and videos.
HTML
<html>
<head>
<meta charset="UTF-8">
<title>Read File as Data URL</title>
</head>
<body>
<input type="file" id="fileInput">
<div>
<h2>Selected Image:</h2>
<img id="imageDisplay"
src="#" alt="Selected Image"
style="max-width: 100%;">
</div>
<script>
document
.getElementById('fileInput')
.addEventListener('change', function (event) {
let file = event.target.files[0];
let reader = new FileReader();
reader.onload = function (event) {
let dataURL = event
.target
.result;
document
.getElementById('imageDisplay')
.src = dataURL;
console.log('Data URL:', dataURL);
};
reader.readAsDataURL(file);
});
</script>
</body>
</html>
Output:
How to read a local text file using JavaScript?In this example:
- An <input> field allows the user to select a file.
- An <img> tag is used to display the selected image.
- When the user selects a file, the change event is triggered.
- A FileReader object is used to read the selected file as a data URL.
- Once the file is read, the result (data URL) is set as the src of the <img> tag, displaying the image.
4. FileReader.readAsBinaryString()
The FileReader.readAsBinaryString() method reads the contents of a file as a raw binary string. This approach is useful when we need to handle binary data directly, such as for processing images, files, or other non-text data formats in JavaScript.
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:
read a local text file using JavaScriptIn this example
- An <input> field (type="file") allows the user to select a file.
- A <pre> tag with id="output" displays the contents of the selected file.
- When a file is selected, the change event triggers.
- A FileReader object (fr) reads the selected file.
- Once the file is read, its content is shown in the <pre> tag by setting textContent to fr.result.
- fr.readAsBinaryString(this.files[0]): Reads the file as a binary string.
File Handling Best Practices
Here are the some of the best practices which we need to follow for file handling:
- Security: JavaScript can only access files that the user selects via the file input. Browsers have strict security measures to prevent malicious scripts from accessing the user's file system.
- File Size Limitation: Most modern browsers have file size limitations for local file reading. If dealing with large files, ensure that the file can be processed in chunks.
- Error Handling: Always include error handling using the onerror event to manage any issues that arise while reading files, such as unsupported file formats or permissions issues.
Note => The File API provides a way to work with files, and the FileReader API allows reading the contents of these files.
Conclusion
The FileReader API is a crucial tool for handling file interactions directly in the browser. Whether you are processing text files, displaying images, or working with binary data, the readAsText(), readAsDataURL(), readAsArrayBuffer(), and readAsBinaryString() methods provide powerful ways to access and manipulate file content.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read