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?
310 Answers
The variable to use would be process.platform
On Mac the variable is set to darwin. On Windows, it is set to win32 (even on 64 bit).
aixdarwinfreebsdlinuxopenbsdsunoswin32android(Experimental, according to the link)
I just set this at the top of my jakeFile:
var isWin = process.platform === "win32"; 14With 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:
2You are looking for the OS native module for Node.js:
4os.platform()
Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.
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()); 2This 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") } 0Works 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.
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)
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';
var isWin64 = process.env.hasOwnProperty('ProgramFiles(x86)'); const path = require('path'); if (path.sep === "\\") { console.log("Windows"); } else { console.log("Not Windows"); } 2