For developers
Real time responses
How to read ping, which arrives line by line without waiting for the end.
Ping at /api/ping answers a little at a time: each line arrives as soon as the server gets it, in the same format as the terminal's ping.
How to read it
- Make the request as usual.
- Read the response body in chunks (a stream), without waiting for the end.
- To stop, cancel the request. The server ends the ping right away.
Browser example
const res = await fetch("/api/ping?host=1.1.1.1");
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
console.log(value);
}Output format
PING 1.1.1.1 (1.1.1.1) 64 bytes from 1.1.1.1: icmp_seq=1 ttl=55 time=14.4 ms 64 bytes from 1.1.1.1: icmp_seq=2 ttl=55 time=14.7 ms
Ping stops on its own after 30 packets. If the server has no ICMP, the test uses TCP connect time instead.
Behind a proxy like nginx, turn off buffering for this route, otherwise the lines only show up at the end.