How to load large local files using JavaScript?
Asked Answered
B

1

13

Is there a way to handle very large files(like 2GB and over) locally in JavaScript without crashing the browser?

*I am aware of the input tag and the FileReader API, but it seems there is nothing like Node.js streams.

Bautista answered 10/11, 2018 at 9:57 Comment(8)
What exactly are you planning on doing with this file? Just curious.Cartierbresson
This is mainly hypothetical for future development at the moment, but the reason I thought of asking this question was because of wanting to extract data from a dump of my Google data. Obviously, any kind of functionality I would use this for is to extract a smaller amount of data at once such as "find all dates when I am at specific location".Bautista
Any reason why you would be asking js to strain under a job that serverside would find trivial?Cramoisy
@Cramoisy No network upload so reduces data costs + can be done on slow network environments. Users can share the processing burden instead of having the server owner burden the load of everyone using the service. Don't like uploading private data to external server.Bautista
You can offload your long running task (large file handling in this case) to Web Workers (developer.mozilla.org/en-US/docs/Web/API/Worker). The web worker runs within another thread (context) therefore it won't block your main thread (browser)Fane
@meteorzeroo Nice tip, but does not solve my issue as "crash" is not referring to a pause in processing due to CPU usage but instead that the max internal memory used by the browser process has been exceeded.Bautista
FileReader.readAsArrayBuffer() is your friend for this situation. This blog is a good reference for your caseFane
@meteorzeroo Thanks. You should add that as the answer.Bautista
F
17

FileReader enables you to read contents of files asynchronously. With respect to large file (2GB in your case), you can use function/method FileReader.readAsArrayBuffer() to read a certain chunk size of a file in the memory hence this won't crash your browser, this blog is a good example.

Fane answered 11/11, 2018 at 10:26 Comment(2)
The important part here is the slice() method of Blob. readAsArrayBuffer will just crash the browser the same if you pass a too big Blob to it.Typist
Few years later, but interestingly, in the current version of chromium, if the slice is too big, the "onload" event is never fired. Instead, the "onerror" event says: "NotReadableError".Estival

© 2022 - 2024 — McMap. All rights reserved.