Search code examples
javascriptnode.jsclosuresnode.js-connect

Could someone explain a function wrapping idiom from howtonode?


I have recently started working with node.js, express & mongodb. Since express uses connect to provide middleware support, I started reading up on middleware and connect.

I came across the following example on howtonode.org:

return function logItHandle(req, res, next) {
 var writeHead = res.writeHead; // Store the original function

 counter++;

 // Log the incoming request
 console.log("Request " + counter + " " + req.method + " " + req.url);

 // Wrap writeHead to hook into the exit path through the layers.
 res.writeHead = function (code, headers) {
   res.writeHead = writeHead; // Put the original back

   // Log the outgoing response
   console.log("Response " + counter + " " + code + " " + JSON.stringify(headers));

   res.writeHead(code, headers); // Call the original
 };

 // Pass through to the next layer
 next(); 
};

Could someone explain to me what is happening in this closure? The author calls it a

wrapping idiom to hook into the call to writeHead

What does that mean?


Solution

  • It's intercepting calls to res.writeHead, adding some logging and then delegating calls to the original res.writeHead.

    It's like a super-simple take on AOP for method interception.