Skip to content

Instantly share code, notes, and snippets.

@Yoric
Created October 3, 2012 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yoric/3827754 to your computer and use it in GitHub Desktop.
Save Yoric/3827754 to your computer and use it in GitHub Desktop.
Writing a file asynchronously by chunks
function writeChunks(path, data/*any typed array*/, chunkSize) {
let promise = OS.File.open(path, {write:true});
let file;
promise = promise.then(function onSuccess(aFile) {
file = aFile;
return loop(0);
});
let view = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
let loop = function loop(pos) {
if (pos <= view.byteLength) {
return Promise.resolve(true);
}
let promise = file.write(view.subarray(pos, chunkSize));
promise = promise.then(function onSuccess(bytes) {
return loop(pos + bytes);
});
return promise;
};
promise = promise.then(function onSuccess() {
file.close();
}, function onError(reason) {
if (file) {
file.close();
}
throw reason;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment