Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

package.json script conditional

I have a node script that checks for some conditions. Lets call it condition.js. I have another script which runs my program, lets call it runner.js. runner.js is referenced by a command in my package.json file under scripts as well condition.js with their own commands. I want the condition.js to run before runner.js. If a certain condition is true (it checks a string for something) in the condition.js when it runs, I want the second script to run after it. If it is not true, I don't want the second script to run. How can I do this in package.json?

like image 975
munchschair Avatar asked Aug 07 '17 18:08

munchschair


People also ask

How do I run a script defined package in json?

To define an NPM script, set its name and write the script under the 'scripts' property of your package. json file: To execute your Script, use the 'npm run <NAME-OF-YOUR-SCRIPT>' command. Some predefined aliases convert to npm run, like npm test or npm start, you can use them interchangeably.

Can you use env variables in package json?

You can use environment values to inject in your package. json like this: Any environment variables that start with npm_config_ will be interpreted as a configuration parameter. For example, putting npm_config_foo=bar in your environment will set the foo configuration parameter to bar.

What is Postinstall?

The postinstall script creates the backout package using the information provided by the other scripts. Since the pkgmk and pkgtrans commands do not require the package database, they can be executed within a package installation.


1 Answers

In condition.js you need to exit() the Node process with a non-zero exit code. Then in your package.json file you can check whether to execute the second script based on the exit code (zero or not):

In your condition.js file:

if (true) {  // use your actual condition
  process.exit(128);
}

Then, in your package.json:

{
  "scripts": {
    "special": "node condition.js && node runner.js"
  }
}

Now you can run npm run special from the command line, the runner.js file will only run if condition.js exits with a zero code (which is the default if the node execution ends normally).

like image 129
Jordan Kasper Avatar answered Oct 30 '22 01:10

Jordan Kasper