New way to readLines? #23495
-
But how do you use the Web Streams API with Deno.stdin and Deno.open? Readlines is very convenient, and I haven't figured out how to update my code yet, eg: async function* readStdin(): AsyncGenerator<InputMessage> {
for await (const line of readLines(Deno.stdin)) {
try {
yield JSON.parse(line);
} catch (e) {
console.error(line);
throw e;
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
CC @iuioiua |
Beta Was this translation helpful? Give feedback.
-
Here's what I'd do when I want to parse jsonl file from the filesystem: import { TextLineStream } from "jsr:@std/[email protected]/text-line-stream";
import { JsonParseStream } from "jsr:@std/[email protected]/json-parse-stream";
using f = await Deno.open("./example.jsonl");
const readable = f.readable
.pipeThrough(new TextDecoderStream()) // decode Uint8Array to string
.pipeThrough(new TextLineStream()) // split string line by line
.pipeThrough(new JsonParseStream()); // parse each chunk as JSON
for await (const data of readable) {
console.log(data.wins);
} Result: ❯ cat example.jsonl
───────┬────────────────────────────────────────────────────────────────────────────────────────────────
│ File: example.jsonl
───────┼────────────────────────────────────────────────────────────────────────────────────────────────
1 │ {"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]}
2 │ {"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]}
3 │ {"name": "May", "wins": []}
4 │ {"name": "Deloise", "wins": [["three of a kind", "5♣"]]}
───────┴────────────────────────────────────────────────────────────────────────────────────────────────
❯ deno run --allow-read=. handle_jsonl.ts
[ [ "straight", "7♣" ], [ "one pair", "10♥" ] ]
[ [ "two pair", "4♠" ], [ "two pair", "9♠" ] ]
[]
[ [ "three of a kind", "5♣" ] ] So basically idea here is that you can use |
Beta Was this translation helpful? Give feedback.
Here's what I'd do when I want to parse jsonl file from the filesystem:
Result: