Node.js 操作系统模块

目录

该模块提供了许多函数,可用于从底层的操作系统和程序运行所在的计算机上检索信息并与其进行交互。

const os = require('os')

有一些有用的属性可以告诉我们一些与处理文件有关的关键事项:

os.EOL 可给出行定界符序列。 在 Linux 和 macOS 上为 \n,在 Windows 上为 \r\n

os.constants.signals 可告知所有与处理过程信号相关的常量,例如 SIGHUP、SIGKILL 等。

os.constants.errno 可设置用于错误报告的常量,例如 EADDRINUSE、EOVERFLOW 等。

可以在 http://nodejs.cn/api/os.html#os_signal_constants 上阅读所有的内容。

现在看一下 os 提供的主要方法:

os.arch()

返回标识底层架构的字符串,例如 armx64arm64

os.cpus()

返回关于系统上可用的 CPU 的信息。

例如:

[
  {
    model: 'Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz',
    speed: 2400,
    times: {
      user: 281685380,
      nice: 0,
      sys: 187986530,
      idle: 685833750,
      irq: 0
    }
  },
  {
    model: 'Intel(R) Core(TM)2 Duo CPU     P8600  @ 2.40GHz',
    speed: 2400,
    times: {
      user: 282348700,
      nice: 0,
      sys: 161800480,
      idle: 703509470,
      irq: 0
    }
  }
]

os.endianness()

根据是使用大端序或小端序编译 Node.js,返回 BELE

os.freemem()

返回代表系统中可用内存的字节数。

os.homedir()

返回到当前用户的主目录的路径。

例如:

'/Users/joe'

os.hostname()

返回主机名。

os.loadavg()

返回操作系统对平均负载的计算。

这仅在 Linux 和 macOS 上返回有意义的值。

例如:

[3.68798828125, 4.00244140625, 11.1181640625]

os.networkInterfaces()

返回系统上可用的网络接口的详细信息。

例如:

{ lo0:
   [ { address: '127.0.0.1',
       netmask: '255.0.0.0',
       family: 'IPv4',
       mac: 'fe:82:00:00:00:00',
       internal: true },
     { address: '::1',
       netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
       family: 'IPv6',
       mac: 'fe:82:00:00:00:00',
       scopeid: 0,
       internal: true },
     { address: 'fe80::1',
       netmask: 'ffff:ffff:ffff:ffff::',
       family: 'IPv6',
       mac: 'fe:82:00:00:00:00',
       scopeid: 1,
       internal: true } ],
  en1:
   [ { address: 'fe82::9b:8282:d7e6:496e',
       netmask: 'ffff:ffff:ffff:ffff::',
       family: 'IPv6',
       mac: '06:00:00:02:0e:00',
       scopeid: 5,
       internal: false },
     { address: '192.168.1.38',
       netmask: '255.255.255.0',
       family: 'IPv4',
       mac: '06:00:00:02:0e:00',
       internal: false } ],
  utun0:
   [ { address: 'fe80::2513:72bc:f405:61d0',
       netmask: 'ffff:ffff:ffff:ffff::',
       family: 'IPv6',
       mac: 'fe:80:00:20:00:00',
       scopeid: 8,
       internal: false } ] }

os.platform()

返回为 Node.js 编译的平台:

  • darwin
  • freebsd
  • linux
  • openbsd
  • win32
  • ...等

os.release()

返回标识操作系统版本号的字符串。

os.tmpdir()

返回指定的临时文件夹的路径。

os.totalmem()

返回表示系统中可用的总内存的字节数。

os.type()

标识操作系统:

  • Linux
  • macOS 上为Darwin
  • Windows 上为 Windows_NT

os.uptime()

返回自上次重新启动以来计算机持续运行的秒数。

os.userInfo()