欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 Node.js 获取用户的操作系统和版本号

最编程 2024-05-06 07:40:11
...

获取操作系统

在 Node.js 中判断操作系统是非常简单的,用 process.platform 即可返回标识操作系统平台的字符串,可能的值为

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

除了这种方法,还可以使用 os 模块的 os.platform() 方法获取,得到的结果是一样的。

获取 Windows 系统版本号

知道操作系统之后,我们还希望获取其版本号,例如如果用户是 windows,我想知道他是用的 win7 还是 win10 呀,这个时候应该怎么办呢?还是要用到 os 模块的 os.release() 方法获取,得到的格式如下:

10.0.18363

格式是 major.minor.build,各版本的对应关系如下:

 Version                                    major.minor   
------------------------------------------ ------------- 
 Windows 10, Windows Server 2016            10.0
 Windows 8.1, Windows Server 2012 R2        6.3
 Windows 8, Windows Server 2012             6.2
 Windows 7, Windows Server 2008 R2          6.1
 Windows Vista, Windows Server 2008         6.0
 Windows XP Professional x64 Edition,       5.2
 Windows Server 2003, Windows Home Server
 Windows XP                                 5.1
 Windows 2000                               5.0

更详细的介绍,可参考官方文档。这里给出一个如何判断 win7 或 win7 及以下的代码:

const os = require('os')
const semver = require('semver')
const platform = os.platform()
const isWindows = platform === 'win32'
const release = os.release()
const isWin7 = isWindows && release.startsWith('6.1')
const win7orOlder = isWindows && semver.lte(release, '6.1')

获取 Mac 系统版本号

但在 Mac 上,os.release() 得到的结果就不准了,比如我 Mac 版本是 11.1,但是 os.release() 返回的是 20.2.0,如果 Mac 版本是 11.5,返回的却是 20.5.0,所以不能用这个方法获取了。不过 Mac 上有一个命令 sw_vers,我们在终端运行结果如下:

$ sw_vers
ProductName:	macOS
ProductVersion:	11.4
BuildVersion:	20F71

可以看到 ProductVersion 那一行展示了精确的版本号,可以用下面的命令提取出来:

$ sw_vers -productVersion
11.4

到这里,代码就出来了:

const { execSync } = require('child_process')
const macVersion = execSync('sw_vers -productVersion', { encoding: 'utf-8' })

Mac 上的版本号对应关系可参考官方文档

推荐阅读