0

I am new to Node.js. Recently, I am building a script as below:

"updateData": "node runFirstScript.js && node runSecondScript.js",
"build:desktop": "npm run updateData env1",
"build:mobile": "npm run updateData env2",

I am expecting runFirstScript.js and runSecondScript.js can get the parameters env1 and env2 while they are executed.

Instead of separating as below:

"updateData1": "node runFirstScript.js",
"updateData2": "node runFirstScript.js",
"build:desktop": "npm run updateData1 env1 && npm run updateData2 env1",
"build:mobile": "npm run updateData1 env2 &&  npm run updateData2 env2",

Is there any optimum solution for this? Thanks

RobC
  • 22,977
  • 20
  • 73
  • 80
Edward
  • 1
  • changing && to & should work, will execute commands sequentially. '|' runs async instead but not all commands will log any output, can ust 'start' to run them in a separate terminal – zergski Aug 26 '22 at 06:50
  • If you're running on _*nix_ (Linux, macOS, etc) you can utilise a [shell function](https://www.gnu.org/software/bash/manual/bashref.html#Shell-Functions). E.g. In your first example change the _updateData_ script to: `"updateData": "func() { node runFirstScript.js \"$1\" && node runSecondScript.js \"$1\"; }; func"` Refer to the _"Solution 1"_ section in my answer [here](https://stackoverflow.com/questions/51388921/pass-command-line-args-to-npm-scripts-in-package-json/51401577#51401577) for further explanation. For cross-platform support you'll need to something akin to _"Solution 2"_. – RobC Aug 26 '22 at 13:59
  • Does this answer your question? [Passing arguments to combined npm script](https://stackoverflow.com/questions/51590079/passing-arguments-to-combined-npm-script) – RobC Aug 26 '22 at 14:18
  • Thanks, @zergski. That doesn't fit my requirement for now. However, it does make me know && v.s &. – Edward Aug 29 '22 at 02:46
  • Thank @RobC. I am working with Windows. I would try with the cross-platform to see whether it works. – Edward Aug 29 '22 at 07:09

1 Answers1

1

Just change && to &,here is the reason what each symbol mean:

  • & is to make the command run in background. You can execute more than one command in the background, in a single go. For eg: Command1 & Command2 & Command3

  • && is to make following commands run only if preceding command succeeds.For eg: Lets say we have Command1 && Command2 && Command3. Command2 will only execute if Command1 succeed.

  • Bonus: ; which is useful in your daily productivity, You can run several commands in a single go and the execution of command occurs sequentially. For eg: Command1; Command2; Command3

  • Thank you! That do help me understand && v.s &. However, I need to make sure script2 runs until script1 is finished. – Edward Aug 29 '22 at 02:45