溫馨提示×

Node.js日志中如何監控網絡延遲

小樊
43
2025-08-26 12:20:45
欄目: 編程語言

在Node.js中,你可以使用第三方庫或者原生模塊來監控網絡延遲。這里有兩種方法:

方法一:使用第三方庫(例如:axios)

  1. 首先,安裝axios庫:
npm install axios
  1. 創建一個名為monitor.js的文件,并添加以下代碼:
const axios = require('axios');

async function checkLatency(url) {
  const startTime = Date.now();
  try {
    await axios.get(url);
    const endTime = Date.now();
    const latency = endTime - startTime;
    console.log(`Latency to ${url}: ${latency}ms`);
  } catch (error) {
    console.error(`Error while checking latency to ${url}:`, error.message);
  }
}

// 使用示例
checkLatency('https://example.com');
  1. 運行monitor.js文件:
node monitor.js

方法二:使用原生http模塊

  1. 創建一個名為monitor_native.js的文件,并添加以下代碼:
const http = require('http');

function checkLatency(url) {
  const parsedUrl = new URL(url);
  const startTime = Date.now();
  const options = {
    hostname: parsedUrl.hostname,
    port: parsedUrl.port || 80,
    path: parsedUrl.path || '/',
    method: 'GET',
  };

  const req = http.request(options, (res) => {
    const endTime = Date.now();
    const latency = endTime - startTime;
    console.log(`Latency to ${url}: ${latency}ms`);
  });

  req.on('error', (error) => {
    console.error(`Error while checking latency to ${url}:`, error.message);
  });

  req.end();
}

// 使用示例
checkLatency('http://example.com');
  1. 運行monitor_native.js文件:
node monitor_native.js

這兩種方法都可以幫助你監控網絡延遲。你可以根據自己的需求選擇合適的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女