I would like to read a file and convert it into a base64 encoded string using the FileReader object. Here\'s the code I use :
var reader = new FileReader();
The below code works sync way to read the file and return its content as text (string)
function SyncFileReader(file) {
let self = this;
let ready = false;
let result = '';
const sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
self.readAsDataURL = async function() {
while (ready === false) {
await sleep(100);
}
return result;
}
const reader = new FileReader();
reader.onloadend = function(evt) {
result = evt.target.result;
ready = true;
};
reader.readAsDataURL(file);
}
Usage :
const fileReader = new SyncFileReader(file);
const arrayBuffer = await fileReader.readAsDataURL();