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:
const os = require('os');
console.log(os.type()); // e.g. Windows_NT, Linux, Darwin, etc.
Reusable function
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.
const os = require('os');
const detectOSType = () => {
const type = os.type();
if (type.startsWith('Windows')) return 'Windows';
if (type.startsWith('Linux')) return 'Linux';
if (type.startsWith('Darwin')) return 'Mac';
return 'UNKNOWN';
};
// Usage example:
console.log(detectOSType()); // e.g. Windows, Linux, Mac and UNKNOWN
Alternative solution
Node.js API provides information about platform that helps in easy way to detect operating system.
const detectOSType = () => {
switch (process.platform) {
case 'win32': return 'Windows';
case 'linux': return 'Linux';
case 'darwin': return 'Mac';
default: return 'UNKNOWN';
}
};
// Usage example:
console.log(detectOSType()); // e.g. Windows, Linux, Mac and UNKNOWN