How to read file contents in javascript variable?

I got a little script to break the text inside "var foo" after every four characters. It is working fine. but my actual data in a text file says "a.txt". How to take all the text of a file in 'var foo'. and write splitting output to another text file?

var foo = "this is sample text !!!"; var arr = []; for (var i = 0; i < foo.length; i++) { if (i % 4 == 0 && i != 0) arr.push(foo.substring(i - 4, i)); if (i == foo.length - 1) arr.push(foo.substring(i - (i % 4), i+1)); } document.write(arr); console.log(arr); 
+4
source share
1 answer

To get the contents of a file, you need to select the file using the input tag.

 <!DOCTYPE html> <head> <meta charset="UTF-8"> </head> <body> <input id="input" type="file" accept="text/plain"> <script src="script.js"></script> </body> 

A good point to read the contents of a file is in the change event.

 const input = document.querySelector("#input"); input.addEventListener("change", () => { const file = input.files.item(0); }); 

To read the contents of a file as a string, you need to convert it.

 function fileToText(file, callback) { const reader = new FileReader(); reader.readAsText(file); reader.onload = () => { callback(reader.result); }; } 

The contents of the file as a string will be available for the callback function. You can create a link and use the click event to load a string into a text file.

 function save(content, fileName, mime) { const blob = new Blob([content], { tipe: mime }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = fileName; a.click(); } 

Here is the complete code

 const input = document.querySelector("#input"); input.addEventListener("change", () => { const file = input.files.item(0); fileToText(file, (text) => { save(text, "fileName.txt", "text/plain"); }); }); function fileToText(file, callback) { const reader = new FileReader(); reader.readAsText(file); reader.onload = () => { callback(reader.result); }; } function save(content, fileName, mime) { const blob = new Blob([content], { tipe: mime }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = fileName; a.click(); } 
 <!DOCTYPE html> <head> <meta charset="UTF-8"> </head> <body> <input id="input" type="file" accept="text/plain"> <script src="script.js"></script> </body> 

You can read more about managing files in JavaScript here: https://www.html5rocks.com/en/tutorials/file/dndfiles/

+3
source

All Articles