测量一次 HTTP 往返需要多长时间
【Measuring how long one HTTP round-trip takes】
以下示例用于追踪 HTTP 客户端(OutgoingMessage)和 HTTP 请求(IncomingMessage)的耗时。对于 HTTP 客户端,它表示从发起请求到接收响应的时间间隔;对于 HTTP 请求,它表示从接收到请求到发送响应的时间间隔:
【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:】
import { PerformanceObserver } from 'node:perf_hooks';
import { createServer, get } from 'node:http';
const obs = new PerformanceObserver((items) => {
items.getEntries().forEach((item) => {
console.log(item);
});
});
obs.observe({ entryTypes: ['http'] });
const PORT = 8080;
createServer((req, res) => {
res.end('ok');
}).listen(PORT, () => {
get(`http://127.0.0.1:${PORT}`);
});'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}`);
});