Last active
March 30, 2023 18:01
-
-
Save subzey/b4f9514faa9dbec9711ebb48aec16267 to your computer and use it in GitHub Desktop.
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
#!/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'); |
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
{ | |
"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