Skip to content

Instantly share code, notes, and snippets.

@modster
Created December 3, 2021 23:59
Show Gist options
  • Save modster/cceba09902a5fee9621c5d1c474c314c to your computer and use it in GitHub Desktop.
Save modster/cceba09902a5fee9621c5d1c474c314c to your computer and use it in GitHub Desktop.
Req and res are streams in and out
// https://nodejs.org/api/stream.html#api-for-stream-consumers
const http = require('http');
const server = http.createServer((req, res) => {
// `req` is an http.IncomingMessage, which is a readable stream.
// `res` is an http.ServerResponse, which is a writable stream.
let body = '';
// Get the data as utf8 strings.
// If an encoding is not set, Buffer objects will be received.
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added.
req.on('data', (chunk) => {
body += chunk;
});
// The 'end' event indicates that the entire body has been received.
req.on('end', () => {
try {
const data = JSON.parse(body);
// Write back something interesting to the user:
res.write(typeof data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(1337);
// $ curl localhost:1337 -d "{}"
// object
// $ curl localhost:1337 -d "\"foo\""
// string
// $ curl localhost:1337 -d "not json"
// error: Unexpected token o in JSON at position 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment