猴子補(bǔ)丁(monkey patch):主要功能就是動態(tài)的屬性的替換,模塊運(yùn)行時替換的功能贤笆。說直接點就是程序功能的追加或者變更。
例子,為res.end添加額外邏輯(clearTimeout)围辙,r又不影響es.end的執(zhí)行結(jié)果吉捶。
function (req, res, next) {
`// 存儲原廠設(shè)置res.end`
var end = res.end
`// res.end 重新賦值`
res.end = function (chunk, encoding) {
`// res.end 恢復(fù)原廠設(shè)置`
res.end = end
` // 重寫的res.end被調(diào)用時夺鲜,其內(nèi)部調(diào)用原廠的res.end`
res.end(chunk, encoding)
`// 增加的額外邏輯`
clearTimeout(timer)
}
}
module.exports = function (opts) {
var time = opts.time || 100;
return function (req, res, next) {
var timer = setTimeout(function () {
console.log('is taking too long to respond', req.method, req.url)
}, time)
` // 猴子補(bǔ)丁 `
var end = res.end
res.end = function (chunk, encoding) {
res.end = end
res.end(chunk, encoding)
clearTimeout(timer)
}
next()
}
}