Created
October 3, 2012 15:55
-
-
Save Yoric/3827754 to your computer and use it in GitHub Desktop.
Writing a file asynchronously by chunks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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