Explain Codes LogoExplain Codes Logo

How to use JavaScript to read local text files and read line by line?

javascript
file-reader
async-processing
stream-processing
Anton ShumikhinbyAnton Shumikhin·Nov 10, 2024
TLDR

Want to read a local text file using JavaScript? We'll utilize FileReader API coupled with a listen to a change event on a file input field - through the readAsText() function, let's convert our file to text and then `split('\n') everything into readable lines. Let's go!

document.querySelector('input[type="file"]').addEventListener('change', function() { if(this.files[0]) { const reader = new FileReader(); reader.onload = e => e.target.result.split('\n').forEach(console.log); reader.readAsText(this.files[0]); } });
<input type="file"/>

Don't forget, security restrictions exist. Local file reads work best when your web page is served via HTTP or HTTPS.

Deep dive into FileReader

Some things must be deeply understood to makefile reading process smooth — let's dive into this world.

About security

There's one thing to remember - every user is a Cage. Not Nicolas Cage (unfortunately), but a Secure Cage. Access to local files is restricted, with web pages needing explicit permission through a file input.

Bring in the FileReader

The secret sauce to every file-oriented mission. The FileReader.readAsText() provides an asynchronous operation to read the content of files.

Error-proofing the code

We're programmers, and bugs are our nemesis. Make sure you handle errors properly. Remember - always with great power comes great onerror callbacks.

Advanced patterns

It's time to geek out on some patterns for more complex cases, like files with different line endings or large files:

  • Regular Expressions: These are like the Swiss army knife for handling text patterns - from splitting content to handling different new line characters.
  • ReadableStream: The name checks out. It provides efficient, and stream-based reading of large files.
  • TextDecoder: No more encoding nightmares! Decode file chunks accurately during the reading process with this magical tool.

From file to webpage

With our lines in hand, storing in an array or an object, and displaying them on a webpage becomes a cakewalk.

const output = document.getElementById('output'); reader.onload = event => { output.textContent = event.target.result; // Display file content like a boss! };

Handling Voldemort-sized files and asynchronous processing

What if the file is as big as Voldemort's crimes? Don't worry, we got it covered.

Stream processing

ReadableStream API comes in handy for Voldemort-sized files. Think of it as the Room of Requirement, flexible and efficient, without crashing your browser's memory:

fetch('/path/to/your/textfile.txt') .then(response => response.body) .then(body => { const reader = body.getReader(); // Process each chunk });

Async control flow

A little bit of async/await magic to simplify asynchronous reading operations for cleaner, Dumbledore-approved code:

async function processFile(file) { const reader = new FileReader(); reader.onload = async event => { for (const line of event.target.result.split('\n')) { await processLine(line); // Always finish reading one line before moving on to the next } }; reader.onerror = error => console.error('Error reading file:', error); reader.readAsText(file); }