如何测量 http.NodeJS 中的 ClientRequest 响应时间

How to measure http.ClientRequest response time in NodeJS?

本文关键字:NodeJS 中的 ClientRequest 响应时间 http 何测量 测量      更新时间:2023-09-26

我正在从我的 NodeJS 应用程序创建 http 请求,如下所示:

var start;
var req = http.request(options, function (res) {
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function (chunk) {
        body += chunk;
    });
    res.on('end', function () {
        var elapsed = process.hrtime(start)[1] / 1000000; // in milliseconds
        console.log(elapsed);
        // whatever
    });
});
req.on('socket', function (res) {
    start = process.hrtime();
});
req.on('error', function (res) {
    // whatever
});
if (props.data) req.write(props.data);
req.end();

我想找出我的请求需要多长时间 - 从(或我能到达的最接近的)请求通过网络的那一刻开始(而不是创建承诺的那一刻),直到"响应结束"事件启动的那一刻。

我很难找到最近的时刻/事件,我可以钩到它来开始测量时间。到目前为止,Http 客户端套接字事件是我最好的选择,但它的描述:

在为此

请求分配套接字后发出。

真的不知道这是否是我正在寻找的事件..所以,我的问题是 - 我这样做是对的,还是我可以使用更好的事件(甚至是更好的方法来做整个事情)?谢谢。

是的,我的理解是socket事件是要走的路。

对于一些证据:在 Node.js HTTP 代码中,this.emit('socket')发生在 this.socket.write(data, encoding) 之前。

那里有一个我不确定的检查:

if (!this.socket.writable) return; // XXX Necessary?

因此,在socket事件处理程序中,您可能希望执行相同的检查,并查看是否返回套接字不可写。