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");
How to read txt file and save it in array in javascript in html
Using FileReader
, get the string line by line and then split it and merge it into the resultArr as follows:
var file = document.getElementById('inputfile');
file.addEventListener('change', () => {
var txtArr = [];
var fr = new FileReader();
fr.onload = function() {
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
txtArr = [...txtArr, ...(lines[line].split(" "))];
}
}
fr.onloadend = function() {
console.log(txtArr);
document.getElementById('output').textContent=txtArr.join("");
}
fr.readAsText(file.files[0]);
})
<!DOCTYPE html>
<html>
<head>
<title>Read Text File</title>
</head>
<body>
<input type="file" name="inputfile"
id="inputfile">
<br>
<pre id="output"></pre>
</body>
</html>
Reading a text file using Javascript
Try this snippet, I just tried and it works :)!
Live Demo (With Input File)
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) { var content = reader.result; //Here the content has been read successfuly alert(content); } reader.readAsText(file); } else { fileDisplayArea.innerText = "File not supported!" }});
<input type="file" id="fileInput">
How to use Javascript to read local text file and read line by line?
Without jQuery:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
HTML:
<input type="file" name="file" id="file">
Remember to put your javascript code after the file field is rendered.
Reading local text file into a JavaScript array
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Read a .txt file and output him in p HTML (with JS)
Try this out!
<input type="file" onchange="readFile(this)" />
<script>
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function () {
document.getElementById("app").innerHTML = `<p>${reader.result}</p>`;
};
reader.onerror = function () {
console.log(reader.error);
};
}
</script>
How can I read a text file with a custom extension using p5js
You can use a FileReader
and the FileReader.readAsText()
method, taking care to pass file.file
from the p5.js callback into it.
file.file
is the "underlying File
object. All normal File
methods can be called on this".
let fileInput;
function setup() {
noCanvas();
noLoop();
// Used to create the file:
// (probably won't work in Stack Snippet)
//const writer = createWriter("saveFile.ctxt");
//writer.write(["Hello World"]);
//writer.close();
fileInput = createFileInput(file => {
const reader = new FileReader();
reader.onload = e => {
console.log(e.target.result); // => Hello World
};
reader.readAsText(file.file);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
Related Topics
Google Maps API V3: How to Remove All Markers
Check If an Element Contains a Class in JavaScript
Jquery/JavaScript Collision Detection
Best Way to Track Onchange As-You-Type in Input Type="Text"
How to Run a Function When the Page Is Loaded
Contenteditable, Set Caret At the End of the Text (Cross-Browser)
Html Form Readonly Select Tag/Input
Disabling Browser Print Options (Headers, Footers, Margins) from Page
Jquery Disable/Enable Submit Button
How to Implement "Select All" Check Box in Html
Browser Detection Versus Feature Detection
How to Correctly Iterate Through Getelementsbyclassname
Link Index.Html Client.Js and Server.Js
How to Load an HTML Page in a Div Using JavaScript
Hide Text in HTML Which Does Not Have Any HTML Tags
Do Dom Tree Elements With Ids Become Global Properties
Determine Timezone from Latitude/Longitude Without Using Web Services Like Geonames.Org