Open In App

How to read a local text file using JavaScript?

Last Updated : 21 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

read
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:

f1
Read a local text file using JavaScript

In 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:

f3
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:

f2
read a local text file using JavaScript

In 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.