Skip to content

Instantly share code, notes, and snippets.

@subzey
Last active March 30, 2023 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save subzey/b4f9514faa9dbec9711ebb48aec16267 to your computer and use it in GitHub Desktop.
Save subzey/b4f9514faa9dbec9711ebb48aec16267 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
const { createServer } = require('http');
function serveStatic(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8',
});
res.end(`
<!doctype html>
<html>
<body>
<script>
window.addEventListener('beforeunload', () => {
navigator.sendBeacon('/beacon/', JSON.stringify({"date": new Date().toISOString()}));
});
</script>
<p><a href="https://example.com/">Navigate away</a>, refresh or close the page.</p>
</body>
</html>
`);
};
function rcvBeacon(req, res) {
const buffers = [
Buffer.from('*** Got beacon! ***\n')
];
req.on('readable', () => {
const chunk = req.read();
if (chunk) {
buffers.push(chunk);
}
});
req.on('end', () => {
buffers.push(Buffer.from('\n'));
process.stdout.write(Buffer.concat(buffers));
});
res.writeHead(201);
res.end();
}
function notFound(req, res) {
res.writeHead(404);
res.end();
}
const server = createServer((req, res) => {
switch (req.url) {
case '/':
return serveStatic(req, res);
case '/beacon/':
return rcvBeacon(req, res);
default:
return notFound(req, res);
}
});
server.on('listening', () => {
process.stdout.write(`Listening on http://${server.address().address}:${server.address().port}/\n`);
});
server.listen(8080, 'localhost');
{
"name": "beacon-test",
"version": "0.0.1-alpha.1",
"bin": "./index.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment