Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In HTML5 is there any way to make Filereader's readAsBinaryString() synchronous

Tags:

html

How to wait till onload event completes

function(){

var filedata=null;     
reader.onload=function(e){
filedata=e.target.result;
};
reader.readAsBinaryString(file);

//I need code to wait till onload event handler gets completed.
return filedata;
}
like image 295
user936553 Avatar asked Sep 09 '11 10:09

user936553


People also ask

What is readasbinarystring in FileReader?

FileReader.readAsBinaryString () The readAsBinaryString method is used to start reading the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the raw binary data from the file.

How do I read a binary string from a file?

FileReader.readAsBinaryString() Jump to: The readAsBinaryString method is used to start reading the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the raw binary data from the file.

What is the FileReader API?

These APIs make it much easier to accomplish tasks like reading and writing files or uploading a file created using JavaScript. In this blog post you are going to learn how to use the FileReader API to read the contents of a file from your local hard drive.

Is there a way to synchronize the main thread with FileReader?

If you need a solution for the main thread that "reads like" a synchronous API, i.e. sequentially, you can wrap the async FileReader in a promise and use async functions (you might need to transpile):


2 Answers

Typical solution to this is to separate your code so, that the part which uses the loaded data is in a separate function, which is then called from the event.

Pseudo-code'ish:

function load() {
    //load here
    reader.onload = function(e) {
        process(e.target.result);
    }
}

function process(result) {
    //finish working here
}
like image 192
Jani Hartikainen Avatar answered Sep 27 '22 20:09

Jani Hartikainen


You can read synchronously using threads (Webworkers in Javascript).

http://www.w3.org/TR/FileAPI/#readingOnThreads

like image 40
adamjk Avatar answered Sep 27 '22 19:09

adamjk