Skip to content

Commit

Permalink
add helper to turn deno.Reader into async iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
bartlomieju committed Oct 31, 2018
1 parent 7c82667 commit 7c8483d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions js/deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export { chdir, cwd } from "./dir";
export { File, open, stdin, stdout, stderr, read, write, close } from "./files";
export {
copy,
readerIterator,
ReadResult,
Reader,
Writer,
Expand Down
29 changes: 28 additions & 1 deletion js/io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface Reader {
* of bytes read (`0` <= `n` <= `p.byteLength`) and any error encountered.
* Even if `read()` returns `n` < `p.byteLength`, it may use all of `p` as
* scratch space during the call. If some data is available but not
* `p.byteLength` bytes, `read()` conventionally returns what is available
* `p.byteLength` , `read()` conventionally returns what is available
* instead of waiting for more.
*
* When `read()` encounters an error or end-of-file condition after
Expand Down Expand Up @@ -115,3 +115,30 @@ export async function copy(dst: Writer, src: Reader): Promise<number> {
}
return n;
}

/**
* Turns `r` into async iterator.
*
* for await (const chunk of readerIterator(reader)) {
* console.log(chunk)
* }
*/
export function readerIterator(
r: Reader
): AsyncIterableIterator<ArrayBufferView> {
const b = new Uint8Array(1024);

return {
[Symbol.asyncIterator]() {
return this;
},

async next(): Promise<IteratorResult<ArrayBufferView>> {
const result = await r.read(b);
return {
value: b.subarray(0, result.nread),
done: result.eof
};
}
};
}

0 comments on commit 7c8483d

Please sign in to comment.