How to Read a Local File Using Javascript in Browser (.txt .json etc)

Published on July 11, 2019

Local files can be opened and read in the browser using the Javascript FileReader object.

Reading a file from the local filesystem can be achieved using Javascript by :

  • Choosing a file from the user's system through <input> file element.
  • Reading the chosen file using FileReader object.

Example — Reading a Local Text File

This demo reads a text file from the local disk :

% read

Download JS code for demo

Reading Local Files Using FileReader Object

The FileReader object, like the name suggests, reads a file. It asynchronously reads the contents of the file, and can read both text and binary file formats.

Furthermore it exposes events which makes it possible to know the read progress of the file, whether reading finished or an error occurred.

<input type="file" id="file-input" />
<button id="read-button">Read File</label>
document.querySelector("#read-button").addEventListener('click', function() {
	if(document.querySelector("#file-input").files.length == 0) {
		alert('Error : No file selected');
		return;
	}

	// first file selected by user
	var file = document.querySelector("#file-input").files[0];

	// perform validation on file type & size if required

	// read the file
	var reader = new FileReader();

	// file reading started
	reader.addEventListener('loadstart', function() {
	    console.log('File reading started');
	});

	// file reading finished successfully
	reader.addEventListener('load', function(e) {
	   // contents of file in variable     
	    var text = e.target.result;

	    console.log(text);
	});

	// file reading failed
	reader.addEventListener('error', function() {
	    alert('Error : Failed to read file');
	});

	// file read progress 
	reader.addEventListener('progress', function(e) {
	    if(e.lengthComputable == true) {
	    	var percent_read = Math.floor((e.loaded/e.total)*100);
	    	console.log(percent_read + '% read');
	    }
	});

	// read as text file
	reader.readAsText(file);
});
  • The load event handles successful reading of the file.
  • The error event handles error while reading the file.
  • The progress event handles reading progress of the file.
  • Text files (TXT, CSV, JSON, HTML etc) can be read with readAsText() method.
    Binary files (EXE, PNG, MP4 etc) can be read using readAsBinaryString() / readAsArrayBuffer() methods.
Reading a File and Getting its Binary Data in Javascript
Loading Comments