Created
January 24, 2021 02:21
-
-
Save bbachi/b9671a93b99b6ef20330a1a15883c548 to your computer and use it in GitHub Desktop.
NodeJS Stream
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 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