I’m trying to build a basic text file reader using JavaScript. My goal is to read a local file and convert each line into a character array. I’m using the following code to attempt a JavaScript read file
approach:
function readTextFile() {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "testing.txt", true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
var allText = rawFile.responseText;
document.getElementById("textSection").innerHTML = allText;
}
}
rawFile.send();
}
It works fine in Firefox, but in Chrome, it throws an XMLHttpRequest Exception 101. What and how should I modify this to make the JavaScript read file functionality compatible across all major browsers, especially when dealing with local files?
Use the File API with <input type="file">
for reliable browser support
Hey! One of the most foolproof ways to implement a javascript read file feature is by letting the user choose a file using an <input type="file">
element.
This method avoids security restrictions like the ones Chrome imposes when you try to access local files directly.
<input type="file" id="fileInput">
<pre id="textSection"></pre>
<script>
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
document.getElementById('textSection').textContent = e.target.result;
};
reader.readAsText(file);
});
</script>
This approach is consistent across Chrome, Firefox, and other browsers, no more XMLHttpRequest issues!
Serve your file through a local development server
So here’s the deal: Chrome blocks local file access due to security policies.
If you’re still keen on using XMLHttpRequest or fetch, you’ll need to serve your file using a local dev server like http-server (Node.js), Python’s http.server, or even live-server in VS Code.
# Example using Node.js
`npx http-server`
Once you’re serving over HTTP, your existing javascript read file logic should work fine in Chrome because it’s no longer treated as a “local file access.”
Use fetch()
as a modern alternative (on a server, not directly from file://)
If you’re working in a hosted or local dev environment, fetch()
is a modern, promise-based alternative to XMLHttpRequest. It simplifies your javascript read file workflow.
etch("testing.txt")
.then(response => response.text())
.then(data => {
document.getElementById("textSection").textContent = data;
})
.catch(error => console.error("Error reading file:", error));
Just remember: this only works when served over HTTP/HTTPS, not directly from a file path like file://.