Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create cross platform scripts (multiple command for single line) in package.json (nodeJs)

issue: in script: we want to check env. variable {dev/test/mock} and do following script run based on it.

if $mock is true the run script start-mock else go on reach real test server


scenario 1: we added commands aggregated in package.json script section

e.g. : "test": "export NODE_ENV=dev; grunt", [on linux]
which is "test": "(SET NODE_ENV=dev) & (grunt)", [on win32]

scenario 2: could be bat/sh script sitting in package and we called them out from package.json

scenario 3: (permanent solution) not sure if its already available out there

something like

get arguments from script section: to give flexibility and freedom to end user.
 e.g. : "test": "solution.env NODE_ENV=dev; solution grunt"

where we can have script to process (input with process.platform) out put depends on OS.


"start-pm2": "if \"%MOCK%\" == \"true\" ( npm run mock & pm2 start process.json --env test ) else ( pm2 start process.json )", [windows] for linux if.. fi enter image description here

like image 632
user139856 Avatar asked Jan 09 '17 13:01

user139856


1 Answers

Lets consider implementation of 3-th solution like e.g.

package.json

"scripts": {
  "command" : "node bin/command.js"
}

bin/command.js

const spawn = require("child_process").spawn
const platform = require("os").platform()
const cmd = /^win/.test(platform)
  ? `${process.cwd()}\\bin\\command.bat`
  : `${process.cwd()}/bin/command.sh`

spawn(cmd, [], { stdio: "inherit" }).on("exit", code => process.exit(code))

depends on environments script will execute command.bat or command.sh

like image 52
Krzysztof Safjanowski Avatar answered Sep 24 '22 16:09

Krzysztof Safjanowski