在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
這兩種方法都可以幫助你監控網絡延遲。你可以根據自己的需求選擇合適的方法。