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!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/javascript-read-files/” title=”Read Files With Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JAVASCRIPT READ FILES

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

 

EXAMPLE 1) READ AS TEXT

1A) 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.

 

1B) 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">.

 

1C) THE DEMO

 

 

EXAMPLE 2) READ AS DATA URL (IMAGE)

2A) 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.

 

2B) 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”.

 

2C) THE DEMO


 

 

EXAMPLE 3) READ AS BINARY DATA

3A) THE HTML

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

 

3B) 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.

 

EXAMPLE 4) READ AS ARRAY BUFFER

4A) THE HTML

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

 

4B) 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.

 

 

EXAMPLE 5) 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="readFileE()">
<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.

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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

 

COMPATIBILITY CHECKS

Yep, reading files is not for the old Internet Exploders.

 

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!

5 thoughts on “How To Read Files In Javascript (Simple Examples)”

  1. Sorry this post, although seemingly simple, is completely incomprehensible. Bravo your language is simple, but the problem is that you start from the assumption that those reading knows WHERE to create an HTML field. Again language is simple but I haven’t a flipping clue where I am supposed to do this. I have only one problem, I have a load of files in .js (long story having to do with a website) and all I want to do is read them, in plain english, not code.
    Anyway thanks

    1. “I came to a coding tutorial but don’t want to read code. Laplace transformation should be as simple as 1 + 1 = 10.”

      “It’s not my fault that I skipped all the basics. I just assume that programming is not technical.”

      Have you not realized that the problem lies within and not outside? 😆

      P.S. Manage your own expectations. Just hire a web developer if you are so unwilling to learn. Cheers!

  2. Hi and thanks for this. In 5) Pick file example there is a typo which breaks the code.

    async function readFileE () {

    The E is in Caps.

    onclick=”readFile()”

    So it gives error : Uncaught ReferenceError: readFile is not defined

Leave a Comment

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