Skip to content

Instantly share code, notes, and snippets.

@lewdev
Created February 28, 2025 21:03
Show Gist options
  • Save lewdev/37483281ece82406a5f2cc3f88a4fbcf to your computer and use it in GitHub Desktop.
Save lewdev/37483281ece82406a5f2cc3f88a4fbcf to your computer and use it in GitHub Desktop.
πŸ“„ Load Local Text File to HTML Page in JavaScript (+bookmarklet πŸ”–)

πŸ“„ Load Local Text File to HTML Page in JavaScript (+bookmarklet πŸ”–)

I wanted to be able to load a text file on a page; specifically, a CSV file for my purposes.

The idea is to load a text file and do some data analysis.

The code uses a built-in browser object FileReader and displays the result. Here's a simple implementation:

<input type="file" accept="text/csv, text/txt" onchange="onFileInput(event)" />
<pre id=o></pre>
<script>
const handleData = text => {
  // do stuff with text data here
  o.innerHTML = text;
};
const onFileInput = e => {
  r = new FileReader();
  r.onload = _ => handleData(r.result);
  r.readAsText(e.target.files[0]);
};
</script>

Bookmarklet

This could be a starting point for a text file loading tool such as viewing a CSV file into a nicely formatted table.

data:text/html,<input type=file accept=text/csv,text/txt onchange="r=new FileReader;r.onload=_=>o.innerHTML=r.result;r.readAsText(event.target.files[0])" /><pre id=o>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment