在Node.js中,你可以使用第三方库或者原生模块来监控网络延迟。这里有两种方法:
方法一:使用第三方库(例如:axios)
npm install axios
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');
monitor.js文件:node monitor.js
方法二:使用原生http模块
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');
monitor_native.js文件:node monitor_native.js
这两种方法都可以帮助你监控网络延迟。你可以根据自己的需求选择合适的方法。