How Does Next() Work In Node.js?
Solution 1:
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.
Solution 2:
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
Post a Comment for "How Does Next() Work In Node.js?"