Skip to content
Advertisement

How to pass input object to webworker so it can read slices from a file Javascript

So I create an input object using

JavaScript

I want to send s_curFile to a web worker so that I can read slices from it on both the main thread and the worker at the same time using XMLHTTPRequest like:

JavaScript

I am only reading the file. So, how would I go about sending s_curFile to the worker so I can do that? I would think you would have to use .postMessage(...) from the main thread to the worker using a SharedArrayBuffer, but how would I populate the buffer? Or is there another means to do it, because I am fairly certain XMLHttpRequest can be done from the worker. (I need this functionality because the size of the local file the user can have is upward of 30 GB, so I can’t have it all in memory due to the per tab memory limitations, and I want the workers to help in processing the sheer amount of data)

Advertisement

Answer

You can simply postMessage() your File object. The underlying data will not be copied over, only the wrapper object.

However note that for reading a File you should not use XMLHttpRequest. In older browsers, you’d use a FileReader (or even FileReaderSync in Web Workers), and their .readAsText() method. In recent browsers you’d use either the File‘s .text() method, that does return a Promise resolving with the content read as UTF-8 text.

However to read a text file as chunk, you need to handle multi-bytes characters. Slicing such character in the middle will break it:

JavaScript

To circumvent that, you need to use a TextDecoder, which is able to keep in memory just the last byte of information to be able to reconstruct the proper character, thanks to its stream option available in the .decode() method.

JavaScript

But TextDecoders can’t be shared across Workers, so they won’t really help us to handle the chunking issue you may face when splitting your file to different Workers. I’m unfortunately not aware of an easy solution for this case, so it’s your call if the speed gain is worth the risk of breaking a few characters, I know that in my area of the globe, the risk can’t be taken because most characters are concerned.

Anyway, here is a solution that does take this risk and will split your file in as many available CPU cores there are, each processing its own chunk as a stream and returning the number of “A”s it found.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement