mirror of
https://github.com/denoland/deno.git
synced 2025-03-03 09:31:22 -05:00
Add helper to turn deno.Reader into async iterator (#1130)
This commit is contained in:
parent
669b1a4e97
commit
162eeca373
3 changed files with 40 additions and 0 deletions
|
@ -7,6 +7,7 @@ export { chdir, cwd } from "./dir";
|
|||
export { File, open, stdin, stdout, stderr, read, write, close } from "./files";
|
||||
export {
|
||||
copy,
|
||||
toAsyncIterator,
|
||||
ReadResult,
|
||||
Reader,
|
||||
Writer,
|
||||
|
|
|
@ -17,3 +17,15 @@ test(async function filesCopyToStdout() {
|
|||
assertEqual(bytesWritten, fileSize);
|
||||
console.log("bytes written", bytesWritten);
|
||||
});
|
||||
|
||||
test(async function filesToAsyncIterator() {
|
||||
const filename = "tests/hello.txt";
|
||||
const file = await deno.open(filename);
|
||||
|
||||
let totalSize = 0;
|
||||
for await (const buf of deno.toAsyncIterator(file)) {
|
||||
totalSize += buf.byteLength;
|
||||
}
|
||||
|
||||
assertEqual(totalSize, 12);
|
||||
});
|
||||
|
|
27
js/io.ts
27
js/io.ts
|
@ -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 toAsyncIterator(
|
||||
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
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue