核心功能
-
返回硬件架構
返回字符串表示系統的硬件架構,常見值包括:'x86_64'
:64 位 x86 架構(Intel/AMD)'armv7l'
:32 位 ARM 架構(如樹莓派 3B)'aarch64'
:64 位 ARM 架構(如樹莓派 4B)'ppc64le'
:64 位 PowerPC 小端架構(IBM 服務器)
-
與
os.arch()
的區別os.machine()
:基于操作系統報告的硬件架構os.arch()
:基于 Node.js 二進制文件編譯時的架構
示例:
在 64 位 ARM Linux 服務器上運行 Node.js:
console.log(os.machine()); // 輸出 'aarch64'(系統架構) console.log(os.arch()); // 輸出 'arm64'(Node.js 架構)
使用場景
-
硬件兼容性檢查
const supportedArchitectures = ['x86_64', 'aarch64']; if (!supportedArchitectures.includes(os.machine())) {console.error('不支持的硬件架構:', os.machine());process.exit(1); }
-
動態配置優化
let config; switch (os.machine()) {case 'x86_64':config = require('./config/x86.json');break;case 'aarch64':config = require('./config/arm.json');break;default:config = require('./config/default.json'); }
-
日志與調試
console.log(`系統信息:- 平臺: ${os.platform()}- 架構: ${os.machine()}- 內核版本: ${os.release()}`);
跨平臺輸出示例
運行環境 | os.machine() 輸出 |
---|---|
64 位 Ubuntu Linux | 'x86_64' |
樹莓派 4B (64 位) | 'aarch64' |
macOS M1/M2 | 'arm64' |
Windows 11 (64 位) | 'AMD64' |
IBM Power9 服務器 | 'ppc64le' |
注意事項
-
容器環境
在 Docker 容器中運行時,os.machine()
返回容器宿主機的架構,而非容器自身的架構。 -
Windows 特殊值
Windows 平臺可能返回'AMD64'
(64 位)或'x86'
(32 位),需注意與 Linux 平臺的命名差異。 -
版本兼容性
os.machine()
在 Node.js 14.14.0+ 版本中穩定支持,建議升級到最新 LTS 版本。
底層實現
- Linux:通過
uname -m
命令獲取 - macOS:通過
sysctl -n hw.machine
獲取 - Windows:通過
GetNativeSystemInfo
API 獲取處理器架構
通過合理使用此 API,可以實現硬件級別的兼容性檢查和配置優化,尤其在需要針對不同架構部署二進制文件時(如 Native 模塊編譯)。