Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file in Javascript without blocking I/O

Tags:

javascript

How can I read a file using FileReader() without it blocking I/O while reading? The following is how I am doing it now:

function readImageFile(imageFile, callback) {
    var reader = new FileReader();
    reader.onload = function(e) {
        callback(e.target.result);
    };
    reader.readAsDataURL(imageFile);
}

Which works fine except that I need to process very large images (> 4k resolution) which takes a considerable amount of time. I can't have user input blocked from using other features on the page while reading.

like image 500
Joey Avatar asked Feb 02 '16 01:02

Joey


2 Answers

I believe FileReader is already asynchronous: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

FileReaderSync would be the synchronous version: https://developer.mozilla.org/en-US/docs/Web/API/FileReaderSync

like image 100
Sanketh Katta Avatar answered Nov 16 '22 18:11

Sanketh Katta


FileReader.readAsDataURL is asynchronous. It's not blocking UI by definition (https://www.w3.org/TR/FileAPI/). But to process a file the computer need to spend some resource, so you need to consider this. It's possible that processing a big file requests a lot of resources.

like image 1
Microfed Avatar answered Nov 16 '22 19:11

Microfed