简体   繁体   中英

nodejs - hook or injection for http response.write

I'm searching for a solution, to monitor the sending/writing process of the http response.write method.

I want to be able to monitor and stop the running process, when an event (in my case a second request with a security token) appears (or not appears).

Is this in general possible, and if so, does anyone have some peace of code for me?

Here is a coffee snipped of the codelines

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()

Is there a way to wrap both of the res.write file, "binary" lines in some kind of function or precess, that can be killed?

kind regards

Sure. You can do something like:

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;
}

Put this code in a middleware something at the top of your express stack, so you can monitor all writes from all middlewares, not just your own.

Another thing:

In your code, you specify Content-Length and Transfer-Encoding: chunked . The two don't go together. The chunked is why Chrome (and any other browser...) wants the 0 at the end: chunked encoding comes in "blocks", and each blocks begins with an ASCII hex representation of its length. The thing ends with an empty chunk (that is: a chunk of length 0 that has no data). You should also add a CR-LF after that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM