Created
August 26, 2026 16:54
-
-
Save cisoun/dfd322e46aebd1e29e4d96cc4f05a177 to your computer and use it in GitHub Desktop.
Minimal Node.js server with JSON support
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
| /** | |
| * Minimal Node.js server with JSON support. | |
| * | |
| * Usage: node server.js | |
| * Client: curl -i -d '{}' 127.0.0.1:8000 | |
| * | |
| * NOTES: | |
| * - `Request` and `Response` classes can be extended. For instance, you can | |
| * extend `Request` to override `json` function in order to raise a | |
| * specific custom error on parsing failure. You'll need then to reconfigure | |
| * the `IncomingMessage` argument of the `createServer` function. | |
| */ | |
| import { | |
| Buffer | |
| } from 'node:buffer'; | |
| import { | |
| createServer, | |
| IncomingMessage, | |
| ServerResponse | |
| } from 'node:http'; | |
| class Request extends IncomingMessage { | |
| json () { | |
| return new Promise((resolve, reject) => { | |
| const data = []; | |
| this.on('data', (chunk) => data.push(chunk)); | |
| this.on('error', (e) => reject(e)); | |
| this.on('end', () => { | |
| try { | |
| resolve(JSON.parse(Buffer.concat(data))); | |
| } catch (e) { | |
| reject(e); | |
| } | |
| }); | |
| }); | |
| } | |
| } | |
| class Response extends ServerResponse { | |
| json (code, data) { | |
| this.writeHead(code, { 'Content-Type': 'application/json' }); | |
| this.end(JSON.stringify(data)); | |
| } | |
| } | |
| createServer({ | |
| IncomingMessage: Request, | |
| ServerResponse: Response | |
| }, async (req, res) => { | |
| // Circular references. | |
| req.res = res; | |
| res.req = req; | |
| // Handle request. | |
| try { | |
| console.log('Reading body...'); | |
| const data = await req.json(); | |
| console.log(`Body: ${JSON.stringify(data)}`); | |
| res.json(200, { message: 'ok' }); | |
| } catch (e) { | |
| res.json(400, { error: e.message }); | |
| }; | |
| }).listen(8000, '0.0.0.0', () => { | |
| console.log('listening...'); | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Raise a specific error on JSON parsing failure: