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:
"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""
If you're using an UNIX-like environment, just use & as the separator:
"dev": "npm run start-watch & npm run wp-server"
Otherwise if you're interested on a cross-platform solution, you could use npm-run-all module:
"dev": "npm-run-all --parallel start-watch wp-server"
From windows cmd you can use start:
"dev": "start npm run start-watch && start npm run wp-server"
Every command launched this way starts in its own window.
You should use npm-run-all (or concurrently, parallelshell), because it has more control over starting and killing commands. The operators &, | are bad ideas because you'll need to manually stop it after all tests are finished.
This is an example for protractor testing through npm:
scripts: {
"webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
"protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
"http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
"test": "npm-run-all -p -r webdriver-start http-server protractor"
}
-p = Run commands in parallel.
-r = Kill all commands when one of them finishes with an exit code of zero.
Running npm run test will start Selenium driver, start http server (to serve you files) and run protractor tests. Once all tests are finished, it will close the http server and the selenium driver.
I've checked almost all solutions from above and only with npm-run-all I was able to solve all problems. Main advantage over all other solution is an ability to run script with arguments.
{
"test:static-server": "cross-env NODE_ENV=test node server/testsServer.js",
"test:jest": "cross-env NODE_ENV=test jest",
"test": "run-p test:static-server \"test:jest -- {*}\" --",
"test:coverage": "npm run test -- --coverage",
"test:watch": "npm run test -- --watchAll",
}
Note run-p is shortcut for npm-run-all --parallel
This allows me to run command with arguments like npm run test:watch -- Something.
EDIT:
There is one more useful option for npm-run-all:
-r, --race - - - - - - - Set the flag to kill all tasks when a task
finished with zero. This option is valid only
with 'parallel' option.
Add -r to your npm-run-all script to kill all processes when one finished with code 0. This is especially useful when you run a HTTP server and another script that use the server.
"test": "run-p -r test:static-server \"test:jest -- {*}\" --",
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:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
// first command is for the cmd.exe, second one is for the bash
"dev": "(start npm run start-watch && start npm run wp-server) || (npm run start-watch & npm run wp-server)",
"start": "npm run dev"
}
Then simple npm start (and npm run dev) will work on all platforms!
If you replace the double ampersand with a single ampersand, the scripts will run concurrently.
How about forking
Another option to run multiple Node scripts is with a single Node script, which can fork many others. Forking is supported natively in Node, so it adds no dependencies and is cross-platform.
Minimal example
This would just run the scripts as-is and assume they're located in the parent script's directory.
// fork-minimal.js - run with: node fork-minimal.js
const childProcess = require('child_process');
let scripts = ['some-script.js', 'some-other-script.js'];
scripts.forEach(script => childProcess.fork(script));
Verbose example
This would run the scripts with arguments and configured by the many available options.
// fork-verbose.js - run with: node fork-verbose.js
const childProcess = require('child_process');
let scripts = [
{
path: 'some-script.js',
args: ['-some_arg', '/some_other_arg'],
options: {cwd: './', env: {NODE_ENV: 'development'}}
},
{
path: 'some-other-script.js',
args: ['-another_arg', '/yet_other_arg'],
options: {cwd: '/some/where/else', env: {NODE_ENV: 'development'}}
}
];
let runningScripts= [];
scripts.forEach(script => {
let runningScript = childProcess.fork(script.path, script.args, script.options);
// Optionally attach event listeners to the script
runningScript.on('close', () => console.log('Time to die...'))
runningScripts.push(runningScript); // Keep a reference to the script for later use
});
Communicating with forked scripts
Forking also has the added benefit that the parent script can receive events from the forked child processes as well as send back. A common example is for the parent script to kill its forked children.
runningScripts.forEach(runningScript => runningScript.kill());
For more available events and methods see the ChildProcess documentation
npm-run-all --parallel task1 task2
edit:
You need to have npm-run-all installed beforehand. Also check this page for other usage scenarios.
Quick Solution
In this case, I'd say the best bet If 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:
{
"name": "npm-scripts-forking-example",
"scripts": {
"bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
"serve": "http-server -c 1 -a localhost",
"serve-bundle": "npm run bundle & npm run serve &"
}
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:
"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",
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:
Much of Node.js lovingly imitates Unix principles
You're on *nix (incl. OS X) and NPM is using a shell anyway
Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs to streams.
step by step guide to run multiple parallel scripts with npm.
install npm-run-all package globally
npm i -g npm-run-all
Now install and save this package within project where your package.json exists
npm i npm-run-all --save-dev
Now modify scripts in package.json file this way
"scripts": {
"server": "live-server index.html",
"watch": "node-sass scss/style.scss --watch",
"all": "npm-run-all --parallel server watch"
},
now run this command
npm run all
more detail about this package in given link
npm-run-all
with installing npm install concurrently
"scripts": {
"start:build": "tsc -w",
"start:run": "nodemon build/index.js",
"start": "concurrently npm:start:*"
},
Use concurrently to run the commands in parallel with a shared output stream. To make it easy to tell which output is from which process, use the shortened command form, such as npm:wp-server. This causes concurrently to prefix each output line with its command name.
In package.json, your scripts section will look like this:
"scripts": {
"start": "concurrently \"npm:start-watch\" \"npm:wp-server\"",
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server"
}
npm install npm-run-all --save-dev
package.json:
"scripts": {
"start-watch": "...",
"wp-server": "...",
"dev": "npm-run-all --parallel start-watch wp-server"
}
More info: https://github.com/mysticatea/npm-run-all/blob/master/docs/npm-run-all.md
Just add this npm script to the package.json file in the root folder.
{
...
"scripts": {
...
"start": "react-scripts start", // or whatever else depends on your project
"dev": "(cd server && npm run start) & (cd ../client && npm run start)"
}
}
... but that will wait for start-watch to finish before running wp-server.
For that to work, you will have to use start on your command. Others have already illustrated but this is how it will work, your code below:
"dev": "npm run start-watch && npm run wp-server"
Should be :
"dev": " start npm run start-watch && start npm run wp-server"
What this will do is, it will open a separate instance for each command and process them concurrently, which shouldn't be an issue as far as your initial issue is concerned. Why do I say so? It's because these instances both open automatically while you run only 1 statement, which is your initial goal.
I ran into problems with & and |, which exit statuses and error throwing, respectively.
Other solutions want to run any task with a given name, like npm-run-all, which wasn't my use case.
So I created npm-run-parallel that runs npm scripts asynchronously and reports back when they're done.
So, for your scripts, it'd be:
npm-run-parallel wp-server start-watch
My solution is similar to Piittis', though I had some problems using Windows. So I had to validate for win32.
const { spawn } = require("child_process");
function logData(data) {
console.info(`stdout: ${data}`);
}
function runProcess(target) {
let command = "npm";
if (process.platform === "win32") {
command = "npm.cmd"; // I shit you not
}
const myProcess = spawn(command, ["run", target]); // npm run server
myProcess.stdout.on("data", logData);
myProcess.stderr.on("data", logData);
}
(() => {
runProcess("server"); // package json script
runProcess("client");
})();
In a package.json in the parent folder:
"dev": "(cd api && start npm run start) & (cd ../client && start npm run start)"
this work in windows
This worked for me
{
"start-express": "tsc && nodemon dist/server/server.js",
"start-react": "react-scripts start",
"start-both": "npm -p -r run start-react && -p -r npm run start-express"
}
Both client and server are written in typescript.
The React app is created with create-react-app with the typescript template and is in the default src directory.
Express is in the server directory and the entry file is server.js
typescript code and transpiled into js and is put in the dist directory .
checkout my project for more info: https://github.com/nickjohngray/staticbackeditor
UPDATE:
calling npm run dev, to start things off
{"server": "tsc-watch --onSuccess \"node ./dist/server/index.js\"",
"start-server-dev": "npm run build-server-dev && node src/server/index.js",
"client": "webpack-dev-server --mode development --devtool inline-source-map --hot",
"dev": "concurrently \"npm run build-server-dev\" \"npm run server\" \"npm run client\""}
You can also use pre and post as prefixes on your specific script.
"scripts": {
"predev": "nodemon run-babel index.js &",
"dev": "webpack-dev-server"
}
And then run:
npm run dev
In my case I have two projects, one was UI and the other was API, and both have their own script in their respective package.json files.
So, here is what I did.
npm run --prefix react start& npm run --prefix express start&
Simple node script to get you going without too much hassle. Using readline to combine outputs so the lines don't get mangled.
const { spawn } = require('child_process');
const readline = require('readline');
[
spawn('npm', ['run', 'start-watch']),
spawn('npm', ['run', 'wp-server'])
].forEach(child => {
readline.createInterface({
input: child.stdout
}).on('line', console.log);
readline.createInterface({
input: child.stderr,
}).on('line', console.log);
});
I have been using npm-run-all for some time, but I never got along with it, because the output of the command in watch mode doesn't work well together. For example, if I start create-react-app and jest in watch mode, I will only be able to see the output from the last command I ran. So most of the time, I was running all my commands manually...
This is why, I implement my own lib, run-screen. It still very young project (from yesterday :p ) but it might be worth to look at it, in your case it would be:
run-screen "npm run start-watch" "npm run wp-server"
Then you press the numeric key 1 to see the output of wp-server and press 0 to see the output of start-watch.
A simple and native way for Windows CMD
"start /b npm run bg-task1 && start /b npm run bg-task2 && npm run main-task"
(start /b means start in the background)
I think the best way is to use npm-run-all as below:
1- npm install -g npm-run-all <--- will be installed globally
2- npm-run-all --parallel server client
How about a good old fashioned Makefile?
This allows you a lot of control including how you manage subshells, dependencies between scripts etc.
# run both scripts
start: server client
# start server and use & to background it
server:
npm run serve &
# start the client
client:
npm start
call this Makefile and then you can just type
make start to start everything up. Because the server command is actually running in a child process of the start command when you ctrl-C the server command will also stop - unlike if you just backgrounded it yourself at the shell.
Make also gives you command line completion, at least on the shell i'm using. Bonus - the first command will always run so you can actually just type make on it's own here.
I always throw a makefile into my projects, just so I can quickly scan later all the common commands and parameters for each project as I flip between them.
Using just shell scripting, on Linux.
"scripts": {
"cmd": "{ trap 'trap \" \" TERM; kill 0; wait' INT TERM; } && blocking1 & blocking2 & wait"
}
npm run cmd
and then
^C will kill children and wait for clean exit.
As you may need to add more and more to this scripts it will become messy and harder to use. What if you need some conditions to check, variables to use? So I suggest you to look at google/zx that allows to use js to create scripts.
Simple usage:
install zx: npm i -g zx
add package.json commands (optional, you can move everything to scripts):
"scripts": {
"dev": "zx ./scripts/dev.mjs", // run script
"build:dev": "tsc -w", // compile in watch mode
"build": "tsc", // compile
"start": "node dist/index.js", // run
"start:dev": "nodemon dist/index.js", // run in watch mode
},
create dev.mjs script file:
#!/usr/bin/env zx
await $`yarn build`; // prebuild if dist is empty
await Promise.all([$`yarn start:dev`, $`yarn build:dev`]); // run in parallel
Now every time you want to start a dev server you just run yarn dev or npm run dev.
It will first compile ts->js and then run typescrpt compiler and server in watch mode in parallel. When you change your ts file->it's will be recompiled by tsc->nodemon will restart the server.
Advanced programmatic usage
Load env variables, compile ts in watch mode and rerun server from dist on changes (dev.mjs):
#!/usr/bin/env zx
import nodemon from "nodemon";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
// load env variables
loadEnvVariables("../env/.env");
await Promise.all([
// compile in watch mode (will recompile on changes in .ts files)
$`tsc -w`,
// wait for tsc to compile for first time and rerun server on any changes (tsc emited .js files)
sleep(4000).then(() =>
nodemon({
script: "dist/index.js",
})
),
]);
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function getDirname() {
return path.dirname(fileURLToPath(import.meta.url));
}
function loadEnvVariables(relativePath) {
const { error, parsed } = dotenv.config({
path: path.join(getDirname(), relativePath),
});
if (error) {
throw error;
}
return parsed;
}
Related
I would like to run the next.js build process directly from the command line without going over the package.json. Is it possible to run it without npm run?
Instead of running npm run build
I would like to run next build directly on the command line.
Cheers for the help.
If you look inside your project's node_modules/.bin directory, you should see an alias for the next command. So if you want to run next build directly without using npm...
Bash:
./node_modules/.bin/next build
Windows Command Prompt:
.\node_modules\.bin\next.cmd build
you can go to package.json and then change the scripts.
"build": "next build",
I figured it out so basically whatever you add at the end of the npm run command gets attached to the npm run command:
"scripts": {
"dev": "next dev",
"build": "next build",
"export": "next build && next export -o",
}
Now I can run
npm export jane-doe-directory
And the application will be exported to that directory.
What is the difference between npm run serve and npm run dev in vuejs. Why should i use npm run serve command to run the project
npm run serve basically is just saying "npm please run the command I defined under the name serve in package.json" the same happens with npm run dev.
Given this the commands can do the exact same thing, similar things, or very different things. Usually they are a shorthand for running a dev server on localhost, but it’s not a rule, only a convention.
So you'll need to check in your package.json file and look for
"scripts": {
"serve": "[list of commands here]",
"dev": "[list of commands here]"
},
this is a snippet from my package.json
"scripts": {
"start": "mkdir BigDirectory",
"build": "mkdir BigDirectory"
},
I've noticed that npm build simply goes to the next new line in terminal (without creating a directory)
While npm start works and creates the "BigDirectory"
Why is npm build non-responsive? Am i perhaps allowed only one single script in my package.json?
I have npm module with following package.json
{
"name": "my-app",
"version": "0.0.0",
"scripts": {
"prepublish": "bower install",
"build": "gulp"
},
"dependencies": {
"express": "~4.0.0",
"body-parser": "~1.0.1"
},
"devDependencies": {
"gulp": "~3.6.0",
"bower": "~1.3.2"
}
}
When I deploy my app to production, I don't want install devDependecies, so, I run npm install --production. But in this case, prepublish script is called, but it doesn't need to, because I use CDN links in production.
How to call postinstall script only after npm install but not after npm install --production?
Newer npm (& Yarn) versions include support for the prepare script that is run after each install run but only in development mode. Also, the prepublish is deprecated. This should be enough:
{
scripts: {
"prepare": "bower install"
}
}
Docs: https://docs.npmjs.com/misc/scripts
I think you cannot choose what scripts are run based on the --production argument. What you can do, however, is supply a script which tests the NODE_ENV variable and only runs bower install if it's not "production".
If you are always in a unix-y environment, you can do it like this:
{
scripts: {
"prepublish": "[ \"$NODE_ENV\" = production ] && exit 0; bower install"
}
}
This only works if you're on a unix-like environment:
NPM sets an environment variable to "true" when install is run with --production. To only run the postinstall script if npm install was not run with --production, use the following code.
"postinstall": "if [ -z \"$npm_config_production\" ]; then node_modules/gulp/bin/gulp.js first-run; fi",
Solution that is less dependent on unix nature of your shell:
"scripts": {
"postinstall": "node -e \"process.env.NODE_ENV != 'production' && process.exit(1)\" || echo do dev stuff"
},
I work with windows, osx and linux so I use a NON environment specific solution to solve this problem:
In the postinstall handler i execute a js script that checks process.env.NODE_ENV variable and does the work.
in my specific case I have to execute a gulp task only in development env:
part of package.json
"scripts": {
"postinstall": "node postinstall"
}
all postinstall.js script
if (process.env.NODE_ENV === 'development') {
const gulp = require('./gulpfile');
gulp.start('taskname');
}
last row of gulpfile.js
module.exports = gulp;
it's important to export gulp from the gulpfile.js because all tasks are in that specific gulp instance.
I have a more general problem - where I want to skip running the postinstall script on local (direct) installs - like when I'm developing the package and run yarn add --dev my-new-dependency.
This is what I came up with. It works with both npm and yarn.
postinstall.js:
const env = process.env;
if (
// if INIT_CWD (yarn/npm install invocation path) and PWD
// are the same, then local (dev) install/add is taking place
env.INIT_CWD === env.PWD ||
// local (dev) yarn install may have been run
// from a project subfolder
env.INIT_CWD.indexOf(env.PWD) === 0
) {
console.info('Skipping `postinstall` script on local installs');
}
else {
// do post-installation things
// ...
}
package.json:
"script": {
"postinstall": "node postinstall.js",
...
Landed here because I had the same issue. Ended up with a solution that tests for the existence of a package under node_modules that I know should only be available in development.
{
"scripts": {
"postinstall": "bash -c '[ -d ./node_modules/#types ] && lerna run prepare || echo No postinstall without type info'"
}
}
This works fine for me conceptually, as the prepare scripts here called by lerna are mainly to ts-to-js compilations.
I'm using if-env module. It's less verbose.
PS: I didn't test it on windows yet.
Install with:
npm i if-env
than in package.json scripts:
"postinstall-production": "echo \"production, skipping...\"",
"postinstall-dev": "echo \"doing dev exclusive stuff\"",
"postinstall": "if-env NODE_ENV=production && npm run postinstall-production || npm run postinstall-dev"
I have two question on JS unit testing:
1) Is there some tool that allows to automaticaly run javascript unit tests when certain files are changed (like for example nodemon restarts node.js on js changes).
2) Is this strategy appropriate (efficient) way to run unit tests?
Thanks,
Alex
For those who are committed to using nodemon, nodemon -x "npm test" has worked for me.
A little explanation
nodemon --help says:
-x, --exec app ........... execute script with "app", ie. -x "python -v".
In our case npm test is set to run tests by configuring our package.json
For example:
"scripts": {
"test": "mocha"
},
When using jest, nodemon is not necessary. Simply set the test script command to jest --watchAll in package.json as follows:
"scripts": {
"test": "jest --watchAll"
}
Check out grunt build system and the watch task. You can setup grunt to watch for file changes and then run any tasks you want (test, lint, compile, etc...).
https://github.com/cowboy/grunt
Some of the ideas are covered in this tutorial. http://javascriptplayground.com/blog/2012/04/grunt-js-command-line-tutorial
Here's a snippet of my package.json:
"scripts": {
"develop": "nodemon ./src/server.js --watch src --watch __tests__ -x \"yarn run test\"",
"test": "mocha ./__tests__/**/*.js --timeout 10000" }
The develop script is my command line to run my express server (entry: ./src/server.js), watch the /src directory which has all my server/API code, watch the /__tests__ directory which as all my specs and lastly tells nodemon to execute the enclosed statement before each restart/run with -x \"yarn run test\"
yarn run test is no different than npm run test. I prefer yarn over npm so that part is up to you. What is important is the \" tags inside the JSON value... without it, it will fail since the argument will be tokenized incorrectly.
This setup allows me to trigger changes from either server/API code or writing/fixing specs and trigger full test run BEFORE restarting the server via nodemon.
Cheers!