使用 Node.js 获取用户操作系统及其版本号

使用 Node.js 获取用户操作系统及其版本号

2021-09-055,823阅读1分钟
 

获取操作系统

在 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,各版本的对应关系如下:

 
arduino
代码解读
复制代码
 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 及以下的代码:

 
js
代码解读
复制代码
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,我们在终端运行结果如下:

 
sh
代码解读
复制代码
$ sw_vers
ProductName:	macOS
ProductVersion:	11.4
BuildVersion:	20F71

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

 
sh
代码解读
复制代码
$ sw_vers -productVersion
11.4

到这里,代码就出来了:

 
javascript
代码解读
复制代码
const { execSync } = require('child_process')
const macVersion = execSync('sw_vers -productVersion', { encoding: 'utf-8' })

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

posted on   漫思  阅读(43)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2023-11-28 特斯拉 “完全开源” 初代 Roadster 设计和工程
2023-11-28 ngnix非常规教程
2022-11-28 QQ浏览器如何关闭鼠标滚轮切换tab
2022-11-28 「ReactNative」原理剖析
2022-11-28 联想浏览器鼠标滚轮切换tab不能关闭的问题
2022-11-28 日本武田制药的新幽门效果如何?
2022-11-28 烟草最早起源于什么地方

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示