How to read a local text file in the browser?
You need to check for status 0 (as when loading files locally with XMLHttpRequest
, you don't get a status returned because it's not from a Webserver
)
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
And specify file://
in your filename:
readTextFile("file:///C:/your/path/to/file.txt");
Read a local text file constantly
Thanks to the File System Access API we can now keep live links to resources on the disk and request their content when we wish. (Previously, Files only kept a snapshot of a file on disk).
So in modern Chrome we can now request access to a file on disk using the window.showOpenFilePicker
method.
This will return a list of handles, from which we will be able to call the getFile()
method to get an up-to-date snapshot of the file on disk.
// must come from an user gesture
onclick = async () => {
if( !("showOpenFilePicker" in self) ) {
throw new Error( "unsupported browser" );
}
const handles = await showOpenFilePicker();
setInterval( async () => {
const file = await handles[0].getFile();
document.getElementById( "log" ).textContent = await file.text();
}, 1000 );
};
Since this API is over-protected, it can't run in cross-domain iframes, so here is an outsourced glitch demo, which currently works only in Chrome.
How to make JS read the contents of a local text file
If you're using node.js you can use the File system api
const fs = require("fs");
let contents = fs.readFileSync("code.txt").toString().split(/\r?\n/);
console.log(contents);
Read a local text file using Javascript
You can use a FileReader
object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
Related Topics
Generating Random Whole Numbers in JavaScript in a Specific Range
Iterate Through Object Properties
How to Return Many Promises and Wait For Them All Before Doing Other Stuff
Cartesian Product of Multiple Arrays in JavaScript
How to Append Something to an Array
Chrome Extension Message Passing: Response Not Sent
Explain the Encapsulated Anonymous Function Syntax
How to Enable Cors in Angularjs
Await Is Only Valid in Async Function
Use of 'Prototype' Vs. 'This' in JavaScript
Error: Can't Set Headers After They Are Sent to the Client
Check Variable Equality Against a List of Values
JavaScript: Do I Need to Put This.Var For Every Variable in an Object
How to Send a Cross-Domain Post Request Via JavaScript
Negative Lookbehind Equivalent in JavaScript
How to Get the Caret Column (Not Pixels) Position in a Textarea, in Characters, from the Start