Node.js os.type() 方法返回一个字符串值,该值指定操作系统类型。例如,返回的字符串在 Linux 操作系统上可以是“Linux”,在 Mac 操作系统上可以是“Darwin”,在 Windows 操作系统上可以是“Windows_NT”。
语法
以下是Node.js os.type()方法的语法 -
os.type()
参数
此方法不接受任何参数。
返回值
此方法返回一个字符串,该字符串指示操作系统的类型。
例在以下示例中,我们尝试通过将 Node.js os.type() 方法记录到控制台来返回当前操作系统的类型。
const os = require('os');
console.log(os.type());
输出
Linux
注意 - 为了获得准确的结果,最好在本地执行上述代码。
执行上述程序后,os.type() 方法返回当前操作系统的类型,如下面的输出所示。
Windows_NT
例
在下面的示例中,
- 我们执行了一个切换案例来获取操作系统的类型。
- 因此,开关会根据 os.type() 方法的输出字符串值检查每种情况,直到找到匹配项。
- 如果没有匹配项,将打印默认条件。
const os = require('os');
const type_of_OS = os.type();
switch(type_of_OS) {
case 'Linux':
console.log("Hi, i'm Linux operating system. Ok bye");
break;
case 'Darwin':
console.log("Hi, i'm Darwin operating system. Ok bye");
break;
case 'Windows_NT':
console.log("Hi, i'm windows_NT operating system. Ok bye");
break;
}
输出
Hi, i'm Linux operating system. Ok bye
注意 - 为了获得准确的结果,最好在本地执行上述代码。
当我们编译并运行上述程序时,os.type() 方法的输出字符串值将为 'Windows_NT'。因此,“Windows_NT”案例被匹配并执行。
Hi, i'm windows_NT operating system. Ok bye