MST

星途 面试题库

面试题:Node.js 中如何使用内置模块实现 HTTP 服务的基本性能监控

在 Node.js 开发中,已知要创建一个简单的 HTTP 服务,利用 Node.js 内置模块,阐述如何对该 HTTP 服务的请求响应时间、吞吐量等基本性能指标进行监控,并给出关键代码示例。
26.7万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试
  1. 监控请求响应时间
    • 原理:在接收到请求时记录开始时间,在发送响应前记录结束时间,两者差值即为响应时间。
    • 关键代码示例
const http = require('http');
const server = http.createServer((req, res) => {
    const startTime = Date.now();
    // 处理请求逻辑
    //...
    res.on('finish', () => {
        const endTime = Date.now();
        const responseTime = endTime - startTime;
        console.log(`Request response time: ${responseTime} ms`);
    });
    res.end('Hello World');
});
const port = 3000;
server.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
  1. 监控吞吐量
    • 原理:记录一段时间内接收和发送的数据量,然后通过计算得到吞吐量(数据量 / 时间)。可以使用定时器定期计算。
    • 关键代码示例
const http = require('http');
let totalReceivedBytes = 0;
let totalSentBytes = 0;
const interval = 1000; // 1 秒
setInterval(() => {
    const throughputReceived = totalReceivedBytes / interval * 1000; // 每秒接收的字节数
    const throughputSent = totalSentBytes / interval * 1000; // 每秒发送的字节数
    console.log(`Throughput (Received): ${throughputReceived} bytes/s`);
    console.log(`Throughput (Sent): ${throughputSent} bytes/s`);
    totalReceivedBytes = 0;
    totalSentBytes = 0;
}, interval);
const server = http.createServer((req, res) => {
    req.on('data', (chunk) => {
        totalReceivedBytes += chunk.length;
    });
    res.on('drain', () => {
        totalSentBytes += res.writableLength;
    });
    res.end('Hello World');
});
const port = 3000;
server.listen(port, () => {
    console.log(`Server running on port ${port}`);
});