In my package.json
I have these two scripts:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
}
I have to run these 2 scripts in parallel everytime I start developing in Node.js. The first thing I thought of was adding a third script like this:
"dev": "npm run start-watch && npm run wp-server"
... but that will wait for start-watch
to finish before running wp-server
.
How can I run these in parallel? Please keep in mind that I need to see the output
of these commands. Also, if your solution involves a build tool, I'd rather use gulp
instead of grunt
because I already use it in another project.
Use a package called concurrently.
npm i concurrently --save-dev
Then setup your
npm run dev
task as so:If you replace the double ampersand with a single ampersand, the scripts will run concurrently.
edit:
You need to have npm-run-all installed beforehand. Also check this page for other usage scenarios.
Using the Concurrently package works, but you do not need it to accomplish this. You can just use a pipe on UNIX based machines run concurrent tasks. I would suggest this method over the other because it saves you from having to add an additional dependency.
I have a crossplatform solution without any additional modules. I was looking for something like a try catch block I could use both in the cmd.exe and in the bash.
The solution is
command1 || command2
which seems to work in both enviroments same. So the solution for the OP is:Then simple
npm start
(andnpm run dev
) will work on all platforms!Quick Solution
In this case, I'd say the best betIf this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this:&
An example of doing this in a partial package.json file:
You'd then execute them both in parallel via
npm run serve-bundle
. You can enhance the scripts to output the pids of the forked process to a file like so:Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:
Further Context RE: Unix Tools & Node.js
If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:
Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from
fs
tostreams
.