"scripts": {
"start": "if [[ $NODE_ENV == 'production' ]]; then node ./bin/www; else nodemon ./bin/www; fi"
},
The above code is used in Unix terminal and I want to use the same in windows cmd
.
But when I try to do that I get NODE_ENV
was unexpected at this time.
I want a proper code which can be executed in windows cmd
.
Consider the following cross-platform solution that works successfully regardless of whether the shell is cmd
(windows) or sh
(*nix). It essentially utilizes node.js to replicate the same conditional logic and to shell out the appropriate command.
"scripts": {
"start": "node -e \"const cmd = process.env.NODE_ENV === 'production' ? 'node' : 'nodemon'; require('child_process').execSync(cmd + ' ./bin/www', { stdio: [0,1,2] });\""
}
Explanation:
The start
npm script does the following:
Utilizes the node.js command line option -e
to evaluate the inline JavaScript.
Using the conditional (ternary) operator, i.e. the part that reads:
const cmd = process.env.NODE_ENV === 'production' ? 'node' : 'nodemon'
We utilize the process.env
property to check the value of the NODE_ENV
environment variable.
If the value of the NODE_ENV
environment variable equals production
we assign the node
command to the cmd
variable. Otherwise we assign the nodemon
command.
In the part that reads:
require('child_process').execSync(cmd + ' ./bin/www', { stdio: [0,1,2] });
require
the builtin execSync()
method from the child_process
module.node ./bin/www
or the nodemon ./bin/www
command based on what was obtained at point 2 (above).stdio
part configures the pipes for stdin, stdout, stderr in the child process.