如何使用Node.js确定当前操作系统

node.js Node.js

乐StafanJim

2020-03-20

我正在编写几个节点外壳脚本,供在平台上开发时使用。我们有Mac和Windows开发人员。是否可以在Node中检查变量以在一个实例中运行.sh文件,在另一个实例中运行.bat?

第2491篇《如何使用Node.js确定当前操作系统》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
斯丁 2020.03.20

对我来说很好

if (/^win/i.test(process.platform)) {
    // TODO: Windows
} else {
    // TODO: Linux, Mac or something else
}

i修饰符用于执行不区分大小写的匹配。

Green小小 2020.03.20

您正在寻找Node.js的OS本机模块:

v4:https//nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform

或v5:https : //nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform

os.platform()

返回操作系统平台。可能的值为“ darwin”,“ freebsd”,“ linux”,“ sunos”或“ win32”。返回process.platform的值。

Stafan路易 2020.03.20

使用的变量是 process.platform

在Mac上,变量返回darwin在Windows上,它返回win32(甚至在64位上)。

当前可能的值为

  • aix
  • darwin
  • freebsd
  • linux
  • openbsd
  • sunos
  • win32

我只是将其设置在我的jakeFile的顶部:

var isWin = process.platform === "win32";

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android