[node.js] How do I determine the current operating system with Node.js

I'm writing a couple of node shell scripts for use when developing on a platform. We have both Mac and Windows developers. Is there a variable I can check for in Node to run a .sh file in one instance and .bat in another?

This question is related to node.js

The answer is


This Works fine for me

var osvar = process.platform;

if (osvar == 'darwin') {
    console.log("you are on a mac os");
}else if(osvar == 'win32'){
    console.log("you are on a windows os")
}else{
    console.log("unknown os")
}

With Node.js v6 (and above) there is a dedicated os module, which provides a number of operating system-related utility methods.

On my Windows 10 machine it reports the following:

var os = require('os');

console.log(os.type()); // "Windows_NT"
console.log(os.release()); // "10.0.14393"
console.log(os.platform()); // "win32"

You can read it's full documentation here: https://nodejs.org/api/os.html#os_os_type


var isWin64 = process.env.hasOwnProperty('ProgramFiles(x86)');

Works fine for me

if (/^win/i.test(process.platform)) {
    // TODO: Windows
} else {
    // TODO: Linux, Mac or something else
}

The i modifier is used to perform case-insensitive matching.


const path = require('path');

if (path.sep === "\\") {
console.log("Windows");
} else {
console.log("Not Windows");
}

Process

var opsys = process.platform;
if (opsys == "darwin") {
    opsys = "MacOS";
} else if (opsys == "win32" || opsys == "win64") {
    opsys = "Windows";
} else if (opsys == "linux") {
    opsys = "Linux";
}
console.log(opsys) // I don't know what linux is.

OS

const os = require("os"); // Comes with node.js
console.log(os.type());

I was facing the same issue running my node js code on Windows VM on mac machine. The following code did the trick.

Replace

process.platform == 'win32'

with

const os = require('os');

os.platform() == 'win32';


when you are using 32bits node on 64bits windows(like node-webkit or atom-shell developers), process.platform will echo win32

use

    function isOSWin64() {
      return process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
    }

(check here for details)


You are looking for the OS native module for Node.js:

v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform

or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform

os.platform()

Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.