summaryrefslogtreecommitdiff
path: root/js
diff options
context:
space:
mode:
authorBartek IwaƄczuk <biwanczuk@gmail.com>2018-10-31 15:29:13 +0100
committerRyan Dahl <ry@tinyclouds.org>2018-10-31 07:29:13 -0700
commit162eeca3734cd88b311150bcaa3f97e120b91f29 (patch)
tree3d4e8fb2d5d46499260ca8b91361301293d7b47c /js
parent669b1a4e97793786b579e8bd5def940359c2536d (diff)
Add helper to turn deno.Reader into async iterator (#1130)
Diffstat (limited to 'js')
-rw-r--r--js/deno.ts1
-rw-r--r--js/files_test.ts12
-rw-r--r--js/io.ts27
3 files changed, 40 insertions, 0 deletions
diff --git a/js/deno.ts b/js/deno.ts
index 346997d4d..e32071ed2 100644
--- a/js/deno.ts
+++ b/js/deno.ts
@@ -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,
diff --git a/js/files_test.ts b/js/files_test.ts
index 9759e0b26..37f63d9fa 100644
--- a/js/files_test.ts
+++ b/js/files_test.ts
@@ -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);
+});
diff --git a/js/io.ts b/js/io.ts
index aa041585b..4e37355bb 100644
--- a/js/io.ts
+++ b/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
+ };
+ }
+ };
+}