How To Read Files In Javascript (Simple Examples)

Welcome to a quick tutorial and examples of how to read files in Javascript. Yes, you read that right – It is possible to read files in client-side Javascript.

To read a file in Javascript:

  1. Create an HTML file field – <input type="file" id="picker"/>
  2. Get the selected file – let selected = document.getElementById("picker").files[0];
  3. Read the selected file.
    • let reader = new FileReader();
    • reader.addEventListener("loadend", () => { let data = reader.result; });
    • reader.readAsText(selected);

That covers the quick basics, and the file reader is also capable of reading images and binary data. Read on for more examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Read Files Useful Bits & Links
Tutorial Video The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

JAVASCRIPT READ FILES

All right, let us now get into the examples of reading files in Javascript.

 

1) READ AS TEXT

THE HTML

1-read-txt.html
<input type="file" value="Choose TXT File" id="demoPickA"
       accept="text/plain" onchange="readFileA()"/>
<div id="demoShowA"></div>

For this first example, we have a simple “choose file” button, and a <div> to show the contents of the selected text file.

 

THE JAVASCRIPT

1-read-txt.html
function readFileA () {
  // (A) GET SELECTED FILE
  let selected = document.getElementById("demoPickA").files[0];
 
  // (B) READ SELECTED FILE
  let reader = new FileReader();
  reader.addEventListener("loadend", () => {
    document.getElementById("demoShowA").innerHTML = reader.result;
  });
  reader.readAsText(selected);
}

This is pretty much the “full version” of the snippet in the introduction, and it should be self-explanatory –

  1. Get the selected file from the input field
  2. Read the file and display the contents in <div id="demoShowA">.

 

THE DEMO

 

 

2) READ AS DATA URL (IMAGE)

THE HTML

2-read-img.html
<input type="file" value="Choose Image File" id="demoPickB"
       accept="image/*" onchange="readFileB()"/>
<img id="demoShowB"/>

Take note that the file field is now restricted to images, and we use an empty <img> to display the selected image instead.

 

THE JAVASCRIPT

2-read-img.html
function readFile() {
  // (A) GET SELECTED FILE
  let selected = document.getElementById("demoFile").files[0];
 
  // (B) READ SELECTED FILE
  let reader = new FileReader();
  reader.addEventListener("load", () => {
    let imgTag = document.getElementById("demoShowB");
    imgTag.src = reader.result;
  });
  reader.readAsDataURL(selected);
}

Look no further, we are pretty much only using readAsDataURL() instead of readAsText() in this example. This will directly get the file data as a base64 encoded string – Rather useful for doing things like “preview selected image”.

 

THE DEMO


 

 

3) READ AS BINARY DATA

THE HTML

3-read-bin.html
<input type="file" value="Choose File" id="demoPickC"
        onchange="readFileC()"/>

 

THE JAVASCRIPT

3-read-bin.html
function readFileC () {
  // (A) GET SELECTED FILE
  let selected = document.getElementById("demoPickC").files[0];
 
  // (B) READ SELECTED FILE
  let reader = new FileReader();
  reader.addEventListener("load", () => {
    var bindata = reader.result;
    console.log(bindata);
  });
  reader.readAsBinaryString(selected);
}

This should be getting stale now – Use readAsBinaryString() to read the file as a binary string. I personally can’t think of a good simple example for this… But this will come in handy for raw data processing and exchange. Maybe create a new blob object, convert it into a ReadableStream.

 

4) READ AS ARRAY BUFFER

THE HTML

4-array-buffer.html
<input type="file" value="Choose File" id="demoPickD"
        onchange="readFileD()"/>

 

THE JAVASCRIPT

4-array-buffer.html
function readFileD () {
  // (A) GET SELECTED FILE
  let selected = document.getElementById("demoPickD").files[0];
  
  // (B) READ SELECTED FILE
  let reader = new FileReader();
  reader.addEventListener("load", () => {
    var buffer = reader.result;
    console.log(buffer);
    console.log(buffer.byteLength);
  });
  reader.readAsArrayBuffer(selected);
}

Finally, we have readAsArrayBuffer(), read the file as an ArrayBuffer. Again, I don’t have a good simple example for ArrayBuffer here – That is out of topic for this tutorial, and it is a boring low-level operation (binary processing). Will leave a link below if you are interested.

 

 

EXTRA) OPEN FILE PICKER PROGRAMMATICALLY

5-pick-file.html
<script>
async function readFileE () {
  // (A) OPEN FILE PICKER
  [handler] = await window.showOpenFilePicker({
    excludeAcceptAllOption: true,
    types: [{
      description: "Text",
      accept: { "text/plain": [".txt", ".text"] }
    }]
  });
 
  // (B) GET SELECTED FILE
  let selected = await handler.getFile();
 
  // (C) READ SELECTED FILE
  let reader = new FileReader();
  reader.addEventListener("loadend", () => {
    document.getElementById("demoShowE").innerHTML = reader.result;
  });
  reader.readAsText(selected);
}
</script>
 
<input type="button" value="Choose File" onclick="readFile()"/>
<div id="demoShowE"></div>

Lastly, we can use window.showOpenFilePicker() to open the “choose a file” dialog box in Javascript. But please take note that it will only work on Chrome, Edge, and Opera at the time of writing – CanIUse.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEATSHEET

Read Files In Javascript (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *