How To Read Txt File And Save It In Array In Javascript In Html
There are many solution to to this but I found few or none in javascript on html webpage. I have a data file called sample.txt located where my html file is. My goal is to load
Solution 1:
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>
Solution 2:
The reason the other methods didn't work is because Javascript does not have access to the filesystem. You need a server side language for this, like NodeJS.
Anyway, here's some pure Javascript code that lets you load text files, split result into a text array for each line and split those again to have data arrays for each line of data. As a little bonus, I also added a method to download everything in a text file again:
function loadFile(input, onloadCallback){
const fr = new FileReader();
fr.onload = onloadCallback;
fr.readAsText(input);
}
/* Save file and force download */
function saveFile(data, fileName){
const blob = new Blob([data], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = fileName;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
/* Working with text files */
function openFile(ev){
loadFile(ev.target.files[0], function(e) {
// Get all the text as a string
const result = e.target.result;
// Make array out of result for each line
const textArray = result.split("\r\n");
// How to add new lines to the array if you want
textArray.push("tan 0.2 time 0.23641");
// Create dataArray for each line
let dataArray = [];
for(let i = 0; i < textArray.length; i++){
const data = textArray[i].split(" ");
dataArray.push(data);
}
// dataArray now contains arrays for each line of data
console.log(dataArray);
// Here's how you'd put a normal array back into a string
const newString = textArray.join("\r\n");
// Finally a way to download a file with the new string inside it
saveFile(newString, 'test.txt');
});
}
Post a Comment for "How To Read Txt File And Save It In Array In Javascript In Html"