使用 Node.js 读取当前 Linux 发行版信息

import os from "node:os";
import fs from "node:fs";

interface ILinuxDistro {
  name: string;
  version: string;
}

/**
 * 获取当前 Linux 发行版的信息。
 *
 * @returns {ILinuxDistro} - 包含 Linux 发行版名称和版本的对象。
 * @throws - 如果当前操作系统不是 Linux 或者无法读取发行版信息时抛出错误。
 *
 * @example
 * ```typescript
 * const distro = getLinuxDistroInfo();
 * console.log(distro.name); // 输出: "Ubuntu"
 * console.log(distro.version); // 输出: "20.04.6 LTS (Focal Fossa)"
 * ```
 */

export const getLinuxDistroInfo = (): ILinuxDistro => {
  // 检查当前操作系统是否为Linux
  if (os.type() !== "Linux") {
    throw new Error(
      `${getLinuxDistroInfo.name}() 函数仅支持 GNU/Linux 操作系统。`
    );
  }

  // 定义将要返回的信息对象
  const linuxDistroInfo: ILinuxDistro = {
    name: "",
    version: ""
  };

  // 读取/etc/os-release文件
  try {
    const data = fs.readFileSync("/etc/os-release", "utf-8");
    const lines = data.split("\n");

    // 解析文件中的信息
    for (const line of lines) {
      if (line.startsWith("NAME=")) {
        linuxDistroInfo.name = line.substring(5).replace(/"/g, "");
      } else if (line.startsWith("VERSION_ID=")) {
        linuxDistroInfo.version = line.substring(11).replace(/"/g, "");
      }
    }
  } catch (error: any) {
    throw new Error(`读取 /etc/os-release 失败: ${error.message}`);
  }

  return linuxDistroInfo;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Luke Paul Na

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值