Skip to content

Instantly share code, notes, and snippets.

@cometkim
Last active November 26, 2024 17:02
Show Gist options
  • Save cometkim/53e5894b690e466437893b8fc1efa23d to your computer and use it in GitHub Desktop.
Save cometkim/53e5894b690e466437893b8fc1efa23d to your computer and use it in GitHub Desktop.
Do your infra hops respect HTTP 103 Early Hints?
import * as http from 'node:http';
import { Readable } from 'node:stream';
import { setInterval } from 'node:timers/promises';
async function* chunksWhile(ms) {
let count = 0;
for await (const startTime of setInterval(1000, Date.now())) {
yield `<div>Looking for your cat... (n=${++count})</div>`;
if (Date.now() - startTime > ms) {
return;
}
}
}
const server = http.createServer((req, res) => {
if (req.url !== '/') {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
return;
}
const stream = Readable.from(chunksWhile(5000));
res.writeEarlyHints({
link: '<https://cataas.com>; rel="preconnect"',
});
res.writeHead(200, {
'Content-Type': 'text/html',
});
stream.pipe(res, { end: false });
stream.on('end', () => {
res.write(`<div>And here's your cat`);
res.write('<div><img src="https://cataas.com/cat" /></div>');
res.write('</div>');
res.end();
});
});
server.listen(3000);
process.on('SIGINT', () => {
server.close(() => {
process.exit(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment