public
Created

Writing a file asynchronously by chunks

  • Download Gist
async.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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;
});
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.