Run several Node.js or npm scripts in parallel
For some projects we need to execute several scripts or npm commands simultaneously. We take the example of a JavaScript client and a Node.js server that need to be launched at the same time. Another example is compiling files and launching a dev server next to it. So we will see the different ways to run several scripts in parallel.
Chained commands in bash
Bash allows multiple commands to be executed simultaneously through chained commands. There are several operators. There is the &&
operator (the AND operator) which allows to execute a sequence of commands. It will execute the second command only if the first command is executed successfully.
# command2 will only run if command1 runs successfully
command1 && command2
There is also the &
operator (the Esperluette or Ampersand operator) which allows us to execute the given commands in the background. It can be used to execute several commands at the same time. The advantage of this operator is that it does not leave us waiting until one of the given commands is completed.
# both commands will run in the background
command1 & command2
We can also use wait
with the &
operator.
wait
is a built-in Unix command that waits for the end of any running process. The wait command is used with a particular process ID. When multiple processes are running in the shell, only the process ID of the last command will be known to the current shell.
If the wait command is executed this time, it will be applied for the last command. If no process ID is given, one will wait for all running child processes to terminate and return the output state.
command1 & command2 & wait
package.json
{
...
"scripts": {
"serve": "command1 & command2 & wait"
},
...
}
Concurrently
Concurrently is an npm package that allows us to run several scripts in parallel.
Installation
# global installation
npm install -g concurrently
# local installation
npm install concurrently
Usage
concurrently "command1 arg" "command2 arg"
package.json
{
...
"scripts": {
"serve": "concurrently \"command1 arg\" \"command2 arg\""
},
...
}
npm-run-all
npm-run-all is an npm package or, as indicated in the documentation, a CLI tool that allows several scripts to be run in parallel or sequentially.
# global installation
npm install -g npm-run-all
# local installation
npm install npm-run-all
Usage
# sequentially equivalent to command1 && command2
npm-run-all command1 command2
# in parellel equivalent to command1 & command2
npm-run-all --parallel command1 command2
package.json
{
...
"scripts": {
"serve": "npm-run-all --parallel command1 command2",
"command1": "echo \"command1 launched\"",
"command2": "echo \"command2 launched\"",
},
...
}
Before you leave…
Thanks for reading! 😊