测量一次 HTTP 往返需要多长时间


以下示例用于跟踪 HTTP 客户端 (OutgoingMessage) 和 HTTP 请求 (IncomingMessage) 花费的时间。 对于 HTTP 客户端,是指发起请求到收到响应的时间间隔,对于 HTTP 请求,是指从接收请求到发送响应的时间间隔:

'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const http = require('node:http');

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});

obs.observe({ entryTypes: ['http'] });

const PORT = 8080;

http.createServer((req, res) => {
  res.end('ok');
}).listen(PORT, () => {
  http.get(`http://127.0.0.1:${PORT}`);
});

The following example is used to trace the time spent by HTTP client (OutgoingMessage) and HTTP request (IncomingMessage). For HTTP client, it means the time interval between starting the request and receiving the response, and for HTTP request, it means the time interval between receiving the request and sending the response:

'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const http = require('node:http');

const obs = new PerformanceObserver((items) => {
  items.getEntries().forEach((item) => {
    console.log(item);
  });
});

obs.observe({ entryTypes: ['http'] });

const PORT = 8080;

http.createServer((req, res) => {
  res.end('ok');
}).listen(PORT, () => {
  http.get(`http://127.0.0.1:${PORT}`);
});