Nam Pham Nam Pham - 5 months ago 9
Javascript Question

How to save a text to file and read it again but save as binary in javascript

I'm building a file saver from a string using FileSaver.js from a SO question

let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data:Blob = new Blob([byteArray], {type: "application/octet-stream"});
var filename:string = filename + '.myext';
saveAs(data, filename, true);


Then I have to read it back to
"my string"
using Javascript's FileReader:

let fr = new FileReader();
fr.onload = (e:FileReaderEvent) => {
let result:any = e.target.result;
//I don't know what I have to do with this type of data to get "my string" back
};
fr.readAsBinaryString(file);

Answer

Edit, Updated

write file

let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
  byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data = new Blob([byteArray], {type: "application/octet-stream"});
saveAs(data, "myfile.abc");

read file

<input type="file">
<script>
 var reader = new FileReader();
 reader.addEventListener("load", function(e) {
   document.body.innerHTML += "<br>" + btoa(e.target.result);
 });
  document.querySelector("input[type=file]")
  .addEventListener("change", function(e) {
     reader.readAsBinaryString(e.target.files[0])
  })
</script>

plnkr http://plnkr.co/edit/0KVhXnd0JpysplDLcAlC?p=preview


You can use TextEncoder(), TextDecoder() or FileReader(), .readAsBinaryString()

var str = "my string";
var encoder = new TextEncoder();
var encodedBytes = encoder.encode(str);
// do file save stuff
var decoder = new TextDecoder();
var decodedBytes = decoder.decode(encodedBytes);

console.log(encodedBytes, decodedBytes);

// alternatively, using `FileReader()`
var reader = new FileReader();
reader.onload = function() {
  console.log("FileReader result:", reader.result)
}
reader.readAsBinaryString(new Blob([encodedBytes]))