{

How to check the current operating system in Nodejs?


How to check the current running operating System Nodejs Example

This example shows how to get the currently running operating system using nodejs code.

Sometimes, We need to run the shell or batch script based on a currently running system.

If OS is windows, use batch(.bat) file. Use shell (.sh) script for Linux and macOS.

Nodejs API programmatically Using command line

How to get the current running Operating System using Nodejs?

There are multiple ways to get OS in Nodejs programmatically, One way is using process. Platform property, Another way to use the Nodejs OS module

  • use process.Platform property process is an object which provides about current runtime environment of a NodeJS program.
console.log(process.platform) // win32

Run the above on my windows machine, gives win32 value.

process.platform returns the following values

- win32 for windows
- Linux for Linux OS
- aix for AIX OS
- openbsd-
- darwin is for MACOS OS
- Android is for Android OS on mobile devices

Here is a complete example

var osValue = process.platform;

if (osValue == 'darwin') {
    console.log("Mac OS");
}else if(osValue == 'win32'){
    console.log("Window OS")
}else if(osValue== 'android') {
    console.log("Android OS")
}else if(osValue== 'linux') {
    console.log("Linux OS")
}
else{
    console.log("Other os")
}

On Running windows, below is an output

Window OS
  • Use Nodejs OS module

Nodejs OS module provides utility methods for the currently running OS.

First, Import the os module using the require keyword in ES5.

use release() function to return current OS version platform() function return OS platform type

var os = require('os');

console.log(os.release()); 
console.log(os.platform()); 


Here is the same above code for ES6. In ES6, import the os module using the import keyword.

import * as Os from 'os'


console.log(Os.release()); 
console.log(Os.platform()); 

Output:

10.0.21996
win32

REPL command line to get the current running Operating System

Here is step by step to get the current OS with the command line.

  • First type node in command line
  • It opens Nodejs REPL command line mode
  • Type os.release() to get version
  • Type os.platform() to get OS platform
A:\work\nodework>node
Welcome to Node.js v14.17.0.
Type ".help" for more information.
> os.release()
'10.0.21996'
> os.platform()
'win32'

Conclusion

Learned multiple ways to get Operating System type using command line and programmatically with examples

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.