HTTP core streams
http core streams
When using createServer
the req
object is readeable, while the res
is writable (not full duplex).
// req: readable, res: writable
http.createServer(function (req, res) {})
// req: writable, res: readable
var req = http.request(opts, function (res) {})
When using the request
module, it's the opposite, the request
(req
) becomes writable and the res
is readable.
http
var http = require('http')
var server = http.createServer(function (req, res) {
req.pipe(process.stdout)
res.end('hello thar!\n')
})
server.listen(5000)
We will create a server, that pipes the contents of a file into a res
object. There are of course lots of better npm modules to serve up static files.
// **** http.js ****
var http = require('http')
const fs = require('fs')
var server = http.createServer(function (req, res) {
if (req.method === 'POST') {
req.pipe(process.stdout)
req.once('end', function () {
res.end('ok\n')
}) else {
// the branch where we are reading from the file
// set the headers
res.setHeader('content-type', 'text/plain')
fs.createReadStream('hello.txt').pipe(res)
}
}
})
// start listening
server.listen(5000)
Then write the client:
// **** http-client.js ****
var http = require('http')
// first, we make a POST request ↴
var req = http.request({
method: 'POST',
// the correct way to specify the url `http://localhost:5000/`
// with req
host: 'localhost'
path: '/',
port: '5000'
},
function(res) {
console.log(res.statusCode)
res.pipe(process.stdout)
})
// req.write() ☛ req.end is a also a shortcut for req.write()
req.end('HELLO\n')
With this, our server will just dump the request to stdout.
Now $ node http-client.js
will print
200
ok
and on the server ($ node http.js
):
HELLO
Now, try to get the file.
// **** http-get-client.js ****
var http = require('http')
var req = http.request({
method: 'GET',
host: 'localhost',
port: 5000,
path: '/'
}, function (res) {
console.log(res.statusCode)
res.pipe(process.stdout)
})
// we do need to end the request
// even though this is a get request
req.end()