我最近开始使用 Node.js、express 和 mongodb。由于express使用connect来提供中间件支持,所以我开始阅读中间件和connect。
我在 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();
};
有人可以向我解释一下这个关闭中发生了什么吗?作者称其为
wrapping idiom to hook into the call to writeHead
这是什么意思?
最佳答案
它拦截对 res.writeHead
的调用,添加一些日志记录,然后将调用委托(delegate)给原始 res.writeHead
。
这就像 AOP 方法拦截的 super 简单。
关于javascript - 有人可以解释一下 howtonode 中的函数包装习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15304437/