[英]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. 我正在寻找解决方案,以监视http response.write方法的发送/写入过程。
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? 有没有办法将res.write文件和“二进制”行包装成某种可以杀死的函数或处理程序?
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
. 在代码中,指定
Content-Length
和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. chunked
是为什么Chrome(和其他任何浏览器...)最后希望为0
的原因:分段编码以“块”形式出现,每个块均以其长度的ASCII十六进制表示形式开头。 The thing ends with an empty chunk (that is: a chunk of length 0 that has no data). 事物以一个空块结尾(即:长度为0的无数据块)。 You should also add a CR-LF after that.
您还应该在此之后添加CR-LF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.