Created
September 9, 2021 07:42
-
-
Save nikostoulas/6243b74e7931062bdf34b91582a93856 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
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 utf 8 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}`); | |
} | |
}); | |
}); | |
//Example taken from: Stream | Node.js v15.11.0 Documentation: https://nodejs.org/api/stream.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment