Created
May 4, 2018 12:55
-
-
Save grishgrigoryan/bf6222d16d72cb28620399d27e83eb22 to your computer and use it in GitHub Desktop.
Helper to iterate over file in browser using for-await-of loop
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
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