Skip to content

Instantly share code, notes, and snippets.

@bbachi
Created January 24, 2021 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbachi/b9671a93b99b6ef20330a1a15883c548 to your computer and use it in GitHub Desktop.
Save bbachi/b9671a93b99b6ef20330a1a15883c548 to your computer and use it in GitHub Desktop.
NodeJS Stream
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+"\n");
// Write back something interesting to the user:
res.write(data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(3003);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment