File: stream.js

package info (click to toggle)
ruby-async-http 0.59.5-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 572 kB
  • sloc: ruby: 4,164; javascript: 40; makefile: 4
file content (56 lines) | stat: -rw-r--r-- 1,283 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const inputStream = new ReadableStream({
	start(controller) {
		interval = setInterval(() => {
			let string = "Hello World!";

			// Add the string to the stream
			controller.enqueue(string);

			// show it on the screen
			let listItem = document.createElement('li');
			listItem.textContent = string;
			sent.appendChild(listItem);
		}, 10000);

		stopButton.addEventListener('click', function() {
			clearInterval(interval);
			controller.close();
		})
	},
	pull(controller) {
		// We don't really need a pull in this example
	},
	cancel() {
		// This is called if the reader cancels,
		// so we should stop generating strings
		clearInterval(interval);
	}
});

fetch("/echo", {method: 'POST', body: inputStream})
	.then(response => {
		const reader = response.body.getReader();
		const decoder = new TextDecoder("utf-8");
		
		function push() {
			reader.read().then(({done, value}) => {
				console.log("done:", done, "value:", value);
				const string = decoder.decode(value);
				
				// show it on the screen
				let listItem = document.createElement('li');
				
				if (done)
					listItem.textContent = "<EOF>"
				else
					listItem.textContent = string;
				
				received.appendChild(listItem);
				
				if (done) return;
				else push();
			});
		};
		
		push();
	});