Last active
November 26, 2024 17:02
-
-
Save cometkim/53e5894b690e466437893b8fc1efa23d to your computer and use it in GitHub Desktop.
Do your infra hops respect HTTP 103 Early Hints?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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