You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NodeJS中获取Windows以太网KB/s级流量统计数据

获取Windows以太网KB/s流量的NodeJS方案
  • 放弃仅能获取数据包数的模块,改用systeminformation模块——它能直接读取网卡的累计收发字节数,通过定时采样计算差值即可得到实时KB/s速率。
  • 具体实现步骤:
    1. 安装依赖:
      npm install systeminformation
      
    2. 编写采样计算代码:
      const si = require('systeminformation');
      
      // 存储上一次采样的字节统计数据
      let prevRxBytes = 0;
      let prevTxBytes = 0;
      
      // 每秒采样一次(和任务管理器刷新频率对齐)
      setInterval(async () => {
        try {
          // 获取所有网卡的统计信息
          const networkStats = await si.networkStats();
          // 筛选以太网网卡(根据实际网卡名称调整匹配规则)
          const ethStats = networkStats.find(stat => 
            stat.name.includes('以太网') || stat.name.includes('Ethernet')
          );
      
          if (ethStats) {
            const currentRx = ethStats.rx_bytes;
            const currentTx = ethStats.tx_bytes;
      
            // 计算1秒内的流量差值,转换为KB/s(1KB = 1024字节)
            const rxKbps = ((currentRx - prevRxBytes) / 1024).toFixed(2);
            const txKbps = ((currentTx - prevTxBytes) / 1024).toFixed(2);
      
            console.log(`接收速率: ${rxKbps} KB/s | 发送速率: ${txKbps} KB/s`);
      
            // 更新上一次的字节数记录
            prevRxBytes = currentRx;
            prevTxBytes = currentTx;
          } else {
            console.log("未找到以太网网卡,请检查网卡名称匹配规则");
          }
        } catch (err) {
          console.error("获取网络数据失败:", err);
        }
      }, 1000);
      
  • 核心逻辑说明:
    • rx_bytes和tx_bytes是网卡自系统启动以来的累计收发字节总量,两次采样的差值除以时间间隔(1秒)就是每秒的流量字节数,再除以1024即可得到KB/s单位的速率。
    • 如果你的以太网网卡名称不包含"以太网"或"Ethernet",可以先打印networkStats数组查看具体名称,再调整筛选条件。

内容的提问来源于stack exchange,提问作者everr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:10:27