Skip to content

Nest 获取 CPU 内存磁盘信息

安装依赖

bash
pnpm install --save node-disk-info

控制器

ts
import { Controller, Get } from "@nestjs/common";
import { CpuallService } from "./cpuall.service";

@Controller("cpuall")
export class CpuallController {
  constructor(private readonly cpuallService: CpuallService) {}

  @Get("cpu")
  async findCpu() {
    return {
      data: await this.cpuallService.findCpu(),
    };
  }

  @Get("mem")
  async findMem() {
    return {
      data: await this.cpuallService.findMem(),
    };
  }

  @Get("disk")
  async findDisk() {
    return {
      data: await this.cpuallService.findDisk(),
    };
  }

  @Get("xitong")
  async xitong() {
    return {
      data: await this.cpuallService.xitong(),
    };
  }
}

服务

ts
import { Injectable } from "@nestjs/common";
import * as os from "os";
import * as nodeDiskInfo from "node-disk-info";
@Injectable()
export class CpuallService {
  // CPU 转换
  findCpu() {
    // 返回的就是数组,数组的个数就是cpu数
    // times.user 用户级别使用的cpu时间
    // times.sys 系统级别使用的cpu时间
    // times.idle 闲置时间
    // 用 reduce 方法累加 cpu 的数量、user、sys、idle 以及总的 cpu 时间。
    // 然后 cpu 的系统使用率就是 sys/total,用户使用率是 user/total 而空置率就是 idle/total。
    const cpus = os.cpus();
    const cpuInfo = cpus.reduce(
      (info, cpu) => {
        info.cpuNum += 1;
        info.user += cpu.times.user;
        info.sys += cpu.times.sys;
        info.idle += cpu.times.idle;
        info.total += cpu.times.user + cpu.times.sys + cpu.times.idle;
        return info;
      },
      { user: 0, sys: 0, idle: 0, total: 0, cpuNum: 0 }
    );
    const cpu = {
      cpuNum: cpuInfo.cpuNum,
      sys: ((cpuInfo.sys / cpuInfo.total) * 100).toFixed(2),
      used: ((cpuInfo.user / cpuInfo.total) * 100).toFixed(2),
      free: ((cpuInfo.idle / cpuInfo.total) * 100).toFixed(2),
    };
    return cpu;
  }

  // 内存 转换
  bytesToGB(bytes) {
    const gb = bytes / (1024 * 1024 * 1024);
    return gb.toFixed(2);
  }
  // 内存 结果
  findMem() {
    const totalMemory = os.totalmem();
    const freeMemory = os.freemem();
    const usedMemory = totalMemory - freeMemory;
    const memoryUsagePercentage = (
      ((totalMemory - freeMemory) / totalMemory) *
      100
    ).toFixed(2);
    const mem = {
      total: this.bytesToGB(totalMemory),
      used: this.bytesToGB(usedMemory),
      free: this.bytesToGB(freeMemory),
      usage: memoryUsagePercentage,
    };
    return mem;
  }

  // 磁盘
  async findDisk() {
    const disks = await nodeDiskInfo.getDiskInfoSync();

    const sysFiles = await disks.map((disk: any) => {
      return {
        dirName: disk._mounted,
        typeName: disk._filesystem,
        total: this.bytesToGB(disk._blocks) + "GB",
        used: this.bytesToGB(disk._used) + "GB",
        free: this.bytesToGB(disk._available) + "GB",
        usage: ((disk._used / disk._blocks || 0) * 100).toFixed(2),
      };
    });
    console.log(sysFiles);
    return sysFiles;
  }

  // 网卡
  getServerIP() {
    const nets: any = os.networkInterfaces();
    for (const name of Object.keys(nets)) {
      for (const net of nets[name]) {
        if (net.family === "IPv4" && !net.internal) {
          return net.address;
        }
      }
    }
  }
  // 返回系统信息
  async xitong() {
    return {
      computerName: os.hostname(),
      computerIp: this.getServerIP(),
      osName: os.platform(),
      osArch: os.arch(),
    };
  }
}

调用

ts
### CPU
GET http://localhost:5000/cpuall/cpu
Content-Type: application/json


### 内存
GET http://localhost:5000/cpuall/mem
Content-Type: application/json


### 硬盘
GET http://localhost:5000/cpuall/disk
Content-Type: application/json


### 系统
GET http://localhost:5000/cpuall/xitong
Content-Type: application/json

总结

  • 这样所有的电脑信息就都获取到了,并且返回了 JSON 格式,方便前端展示。