rog3r rog3r - 6 months ago 30
Node.js Question

How to run npm sh script on Windows and Unix

I want to run a

sh
script that detects my
npm
version via
npm scripts
.
I have the following script and it works cool:

if [ $(npm -v | cut -c 1 | awk '{print $1\"<3\"}' | bc -l) != 0 ]; then echo '[ERROR] You need npm version @>=3\n' && false; fi


But this script works only on *NIX when I run the script on windows I got a error:

$(npm was unexpected at this time.


I want to detect if I'm running the script on Windows then don't execute the script, I tried this, but again only works on *NIX:

if [ 'uname -s' != CYGWIN* ]; then if [ $(npm -v | cut -c 1 | awk '{print $1\"<3\"}' | bc -l) != 0 ]; then echo '[ERROR] You need npm version @>=3\n' && false; fi; fi


Then I got:

'uname was unexpected at this time.


I was checking that the equivalent of
uname
on windows is
systeminfo


But if I use
systeminfo
then I got the undefined on *NIX.

Any ideas of how can I make this script work on Windows && *NIX?

Answer

If you want to execute your bash script on a platform that is not Windows you could check the platform with node itself (assuming that node is installed) using os.platform()

scripts: {      
  checkNpmVersion: "node -e \"process.exit(require('os').platform() === 'win32')\" && ./check-npm.sh"
}

Or even better you could write your a little script that works on any platform (again assuming that node is installed)

// check-npm.js
const exec = require('child_process').exec

exec('npm -v', function (err, stdout, stderr) {
  if (err) throw err
  if (stdout.match(/^3/)) throw "npm>3 required"
})

And in the scripts field

scripts: {      
  checkNpmVersion: "node check-npm.js"
}

Tested on Win7 with Node v4.4.5 and npm 2.15.5

Comments