簡體   English   中英

nodejs-HTTP response.write的掛鈎或注入

[英]nodejs - hook or injection for http response.write

我正在尋找解決方案,以監視http response.write方法的發送/寫入過程。

我希望能夠監視和停止正在運行的進程,當一個事件(對於我來說是帶有安全令牌的第二個請求)出現(或不出現)時。

通常這是可能的嗎?如果可以,那么有人能為我提供一些安全的代碼嗎?

這是代碼行中的一杯咖啡

if req.headers.range?
    console.log "serve range request from cache"
    # browser wants chunged transmission
    range = req.headers.range
    parts = range.replace(/bytes=/, "").split "-"
    partialstart = parts[0]
    partialend = parts[1]
    total = file.length
    start = parseInt partialstart, 10
    end = if partialend then parseInt partialend, 10 else total - 1

    header["Content-Range"] = "bytes #{start}-#{end}/#{total}"
    header["Accept-Ranges"] = "bytes"
    header["Content-Length"]= (end-start)+1
    header['Transfer-Encoding'] = 'chunked'
    header["Connection"] = "close"

    res.writeHead 206, header
    # yeah I dont know why i have to append the '0'
    # but chrome wont work unless i do
    res.write file.slice(start, end)+'0', "binary"
  else
    console.log "serve normal request from cache"
    # reply to normal un-chunked request
    res.writeHead 200, header
    res.write file, "binary"
    console.log err if err
  res.end()

有沒有辦法將res.write文件和“二進制”行包裝成某種可以殺死的函數或處理程序?

親切的問候

當然。 您可以執行以下操作:

origWrite = res.write

res.write = function(buffer, encoding) {
    // do some monitoring, starting, stopping, whatever you like
    retval = origWrite(buffer, encoding);
    // do some more monitoring, starting, stopping, whatever you like
    return retval;
}

將此代碼放在快速堆棧頂部的中間件中,這樣您就可以監視所有中間件的所有寫入,而不僅僅是您自己的。

另一件事:

在代碼中,指定Content-LengthTransfer-Encoding: chunked 兩者不在一起。 chunked是為什么Chrome(和其他任何瀏覽器...)最后希望為0的原因:分段編碼以“塊”形式出現,每個塊均以其長度的ASCII十六進制表示形式開頭。 事物以一個空塊結尾(即:長度為0的無數據塊)。 您還應該在此之后添加CR-LF。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM