EN
Node.js - detect operating system name (Windows, Linux, macOS)
8 points
In this short article, we would like to show how to detect used operating system in Node.js application.
Quick solution:
xxxxxxxxxx
1
const os = require('os');
2
3
console.log(os.type()); // e.g. Windows_NT, Linux, Darwin, etc.
In this section, you can find function that lets in simple way to detect normalised operating system name omitting details, e.g. NT
postfix for Windows, etc.
xxxxxxxxxx
1
const os = require('os');
2
3
const detectOSType = () => {
4
const type = os.type();
5
if (type.startsWith('Windows')) return 'Windows';
6
if (type.startsWith('Linux')) return 'Linux';
7
if (type.startsWith('Darwin')) return 'Mac';
8
return 'UNKNOWN';
9
};
10
11
12
// Usage example:
13
14
console.log(detectOSType()); // e.g. Windows, Linux, Mac and UNKNOWN
Node.js API provides information about platform that helps in easy way to detect operating system.
xxxxxxxxxx
1
const detectOSType = () => {
2
switch (process.platform) {
3
case 'win32': return 'Windows';
4
case 'linux': return 'Linux';
5
case 'darwin': return 'Mac';
6
default: return 'UNKNOWN';
7
}
8
};
9
10
11
// Usage example:
12
13
console.log(detectOSType()); // e.g. Windows, Linux, Mac and UNKNOWN