2013-03-08 64 views
1

我最近開始使用node.js,表示& mongodb。由於express使用connect來提供中間件支持,我開始閱讀中間件並連接。有人可以解釋howtonode包裝成語的函數嗎?

我碰到下面的例子來到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(); 
}; 

有人能向我解釋什麼是在這個封閉發生?筆者稱其爲

包裝成語掛接到調用writeHead

這是什麼意思?

回答

2

它攔截到res.writeHead的呼叫,添加一些日誌記錄,然後將呼叫委託給原始res.writeHead

這就像一個超級簡單的方法攔截AOP。

+0

感謝兩個傢伙!我只接受@matt的回答,因爲它不僅解釋了發生了什麼,而且讓我瞭解了AOP,現在我已經有了一些新的材料可供使用。 – zeusdeux 2013-03-11 21:31:46

1

讓我們分解這到底是怎麼

wrapping idiom to hook into the call to writeHead 

發生在標準表達流,請求(REQ)接收和響應(RES )準備。的(REQRES)一對可通過一系列過濾器系列,可以修改REQ和準備RES級聯。

在流程中的一點上,res將被視爲已充分準備,以便可以將響應的標題發送給客戶端。將爲此目的調用函數res.writeHead *。

發送這一功能是功能(代碼,頭),爲了記錄那些即將頭的原型,你需要掛接在這個非常時刻的代碼,做一個

console.log("Response " + code + " " + JSON.stringify(headers)); 

在某種程度上,如果在代碼中orgininal功能是

res.writeHead = function(code, headers) { 
    // original code 
} 

你想用

替換此代碼

以某種方式,您希望在writeHead函數的開始處「插入」一段代碼。

但是,您不應該嘗試修改原始的writeHead代碼,因爲您甚至可能不知道該代碼的寫入位置,也不想開始查看。所以你想劫持這個函數:當一段代碼調用res.writeHead時,你希望你的函數被調用。

一個辦法來這簡直是

return function logItHandle(req, res, next) { 
    res.writeHead = function (code, headers) { 
     console.log("Response " + code + " " + JSON.stringify(headers)); 
    } 
    next(); 
} 

,但如果你只有做到這一點你到有點麻煩,因爲原始writeHead代碼丟失,也不會被調用。因此標題將被記錄,但不會發送到客戶端!

,你需要一種方法來「記住」的原代碼,並在您writeHead變種結束叫它:

return function logItHandle(req, res, next) { 

    // save the original writeHead function so that it can be referenced in the closure 
    var originalWriteHead = res.writeHead; 

    res.writeHead = function (code, headers) { 

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

     // make as if our hook never existed in the flow 
     res.writeHead = originalWriteHead ; 

     // call the original writeHead because otherwise the external code 
     // called our implementation of writeHead instead of the original code 
     res.writeHead(code, headers); 

    } 
    next(); 
} 
相關問題