Skip to content

Instantly share code, notes, and snippets.

@grishgrigoryan
Created May 4, 2018 12:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grishgrigoryan/bf6222d16d72cb28620399d27e83eb22 to your computer and use it in GitHub Desktop.
Save grishgrigoryan/bf6222d16d72cb28620399d27e83eb22 to your computer and use it in GitHub Desktop.
Helper to iterate over file in browser using for-await-of loop
interface IConfig{
chunkSize:number
}
class IterableFile implements AsyncIterable<string>{
private reader : FileReader;
private file:File
private config : IConfig = {chunkSize : 64 * 1024}
constructor( file:File,config :Partial<IConfig> = {}){
this.file = file
this.reader = new FileReader();
Object.assign(this.config, config)
}
[Symbol.asyncIterator]() {
return this.readFile();
}
get chunkSize(){
return this.config.chunkSize;
}
get fileSize(){
return this.file.size;
}
readBlobAsText(blob) : Promise<string>{
return new Promise((resolve,reject)=>{
this.reader.onload = (e:any)=>{
e.target.result && resolve(e.target.result);
e.target.error && reject(e.target.error);
};
this.reader.readAsText(blob);
})
}
async* readFile() {
let offset = 0;
let blob;
let result;
while(offset < this.fileSize){
blob = this.file.slice(offset, this.chunkSize + offset);
result = await this.readBlobAsText(blob);
offset += result.length;
yield result;
}
}
}
// ***Usage***
// let it = new IterableFile(file)
// for await (const chunk of it) {
// console.log(chunk)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment