I recently read a blog in Nodejitsu and I am wondering how this piece of code works.
var fs = require('fs'),
http = require('http'),
httpProxy = require('../lib/node-http-proxy');
module.exports = function (logging) {
// Code here is run when the middleware is initially loaded.
var logFile = fs.createWriteStream('./requests.log');
return function (request, response, next) {
// Code here is run on each request.
if (logging) {
logFile.write(JSON.stringify(request.headers, true, 2));
}
next();
}
}
And the explanation given for this piece of code is:
This middleware is for very simple logging – it will write the headers of each request to a log file.
the above module exported can be used as,
httpProxy.createServer(
require('./example-middleware')(true),
8000, 'localhost'
).listen(9000)
How is the code in the above method with next() invoked in every request? The usage is pretty simple: require the above module and it gets invoked every time.
I’ll simplify the actual process but the gist of it:
When a request comes in, node passes the request and response object to the first middleware in the middleware stack. If that middleware sends a response or closes the connection in any way, then subsequent middleware are not called. Otherwise, that middleware has to tell node it’s finished doing it’s job to keep on moving through the middleware stack, so you call next() within your middleware to tell it to continue processing middleware.