简体   繁体   中英

How does next() work in Node.js?

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.

Okay, so this is a pretty common thing. What this module contains is a single function, specified by this line, where we set module.exports to a function, module.exports = function (logging) { . The function returned by the module (and therefore returned by require() ) returns another function, which is the middleware for the HTTP proxy (this middleware allows you to transforms the request). This middleware function gets called for every HTTP request made to the server. Quickredfox's answer provides a fairly good explanation of middlewares.

So the require('./example-middleware')(true) actually calls the function assigned to module.exports , but does not call the function inside that, which is returned immediately and passed as a middleware into the httpProxy.createServer function. This is a good way to set up some options for your middleware using closures. If you have any more questions, feel free to comment. :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM