How to read file content in a javascript variable? -


i got small script split text inside 'var foo' after every 4 characters. working fine. actual data in text file 'a.txt'. how take entire file text in 'var foo'. , write split output text file?

var foo = "this sample text !!!";  var arr = []; (var = 0; < foo.length; i++) {     if (i % 4 == 0 && != 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); 

to content of file need select file using 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 moment read content of file in change event.

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

to read content of file string need convert it.

function filetotext(file, callback) {   const reader = new filereader();   reader.readastext(file);   reader.onload = () => {     callback(reader.result);   }; } 

the content of file string available the callback function. can create link , use click event download string text file.

function save(content, filename, mime) {   const blob = new blob([content], {     tipe: mime   });   const url = url.createobjecturl(blob);   const = document.createelement("a");   a.href = url;   a.download = filename;   a.click(); } 

here 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 = 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 manipulating files in javascript here: https://www.html5rocks.com/en/tutorials/file/dndfiles/


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -