-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.sx
More file actions
22 lines (19 loc) · 837 Bytes
/
Copy pathfetch.sx
File metadata and controls
22 lines (19 loc) · 837 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// fetch and Web Streams. Run it: sxn examples/fetch.sx
//
// fetch is the global one from the Fetch standard, backed by libcurl. The
// response body is a real ReadableStream, so it can be consumed a chunk at a
// time instead of all at once.
const res: Response = await fetch("https://example.com/");
console.log(res.status, res.headers.get("content-type"));
// Read it as text, in whole.
const html: string = await res.text();
console.log(`${html.length} bytes`);
// Or a chunk at a time, decoding as the bytes arrive.
const streamed: Response = await fetch("https://example.com/");
let mut chunks: number = 0;
let mut characters: number = 0;
for await (const chunk of streamed.body.pipeThrough(new TextDecoderStream())) {
chunks += 1;
characters += chunk.length;
}
console.log(`${chunks} chunk(s), ${characters} characters`);