Languages
[Edit]
EN

Node.js - detect operating system name (Windows, Linux, macOS)

8 points
Created by:
Krzysiek
741

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

 

References

  1. Node.js process.platform - API Docs

Alternative titles

  1. Node.js - detect operating system type (Windows, Linux, macOS)
  2. Node.js - detect OS type (Windows, Linux, macOS)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join