Last active
March 21, 2025 14:01
-
-
Save timoschinkel/096ea762f087f27a23a5da2113a85d65 to your computer and use it in GitHub Desktop.
Minimal HTTP server using vanilla JavaScript
This file contains hidden or 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
'use strict'; | |
import { createServer } from 'node:http'; | |
/* | |
* Usage: | |
* node server.js | |
* | |
* This will pick a random available port on your local machine. You can steer the port and host using environment variables: | |
* PORT=8080 HOST=localhost node server.js | |
* | |
* During development you can use `--watch` to automatically restart the server on code change. When using this I recommend | |
* specifying a port, otherwise the hot reload will likely pick another port. | |
*/ | |
const port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined; | |
const host = process.env.HOST ?? '0.0.0.0'; | |
/** | |
* @param {import('node:http').IncomingMessage} request | |
* @param {import('node:http').ServerResponse} response | |
* @return {Promise<void>} | |
*/ | |
const handler = async (request, response) => { | |
console.debug('incoming request', request.url); | |
let payload = ''; | |
request.on('data', (chunk) => { payload += chunk; }); | |
request.on('end', () => { | |
console.debug('received data', payload); | |
/* | |
* This is where the request is handled. Any routing should be done in here as well. | |
*/ | |
response.writeHead(200, {'Content-Type': 'text/plain'}); | |
response.write('OK'); | |
response.end(); | |
}); | |
} | |
const server = createServer(handler); | |
server.listen(port, host, () => { | |
console.log(`Listening on port http://${server.address().address}:${server.address().port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment