javascripthtmlfilereader

Read a file synchronously in JavaScript


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();
reader.onloadend = function(evt) {  
    // file is loaded
    result_base64 = evt.target.result; 
};
reader.readAsDataURL(file);

But in this case, I get the result of the conversion in the event handler (onloadend event). I would like a synchronous method. Is there a way the readAsDataURL method can return the value of the result_base64 variable directly?


Solution

  • Synchronous tasks (blocking) are generally bad. If there is no real reason to do that synchronously, I strongly recommend you to use the event callback.

    Imagine your file is broken and the HTML5 api cant read, it wont give you the result. It would break your code and block the site. Or, someone could select a 10GB file, which would freeze your HTML page until the file is completely loaded. With that asynchronous event handler you are able to catch possible errors.

    To work around limitations with callbacks, i use a simple trick:

    var ready = false;
    var result = '';
    
    var check = function() {
        if (ready === true) {
             // do what you want with the result variable
             return;
        }
        setTimeout(check, 1000);
    }
    
    check();
    
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        // file is loaded
        result = evt.target.result;
        
        ready = true;
    };
    reader.readAsDataURL(file);
    

    the check function, checks every second if the ready flag variable is set to true. If so, you can be sure the result is available.

    It may not be best practice to do so, but i made a webapp using this technique about 30 times with more than 10 setTimeouts at the same time running, and experienced no problem until now.