How to execute 'npm run' command programmatically?

Javascriptnode.js

Javascript Problem Overview


I have some custom testing script, which I can run with npm run test command, which executes some Node script for starting e2e/unit tests. But before it I must start webpack dev server with npm run dev (it's a some custom Node script too, details doesn't matter) in other terminal window. So, I want to omit npm run dev manually executing and move it to custom npm run test script, i.e. I want to execute webpack dev server programmatically in Node script. How can I execute npm run dev programmatically using Node script and stop it then? Thanks in advance!

"dev": "node node_modules/webpack-dev-server/bin/webpack-dev-server.js --host 0.0.0.0 --history-api-fallback --debug --inline --progress --config config/config.js"

Javascript Solutions


Solution 1 - Javascript

You can use exec to run from script

import {series} from 'async';
const {exec} = require('child_process');

series([
 () => exec('npm run dev'),
 () => exec('npm run test')
]); 

Solution 2 - Javascript

Just install npm:

npm install npm

Then in your program:

npm.commands.run('dev', (err) => { ... });

See the source for more info. The npm.command object is an unofficial API for npm. Note that using exec or spawn to execute npm is safer, since the API is unofficial.

Solution 3 - Javascript

Here is a solution that should work reliably across all platforms. It's also very concise. Put this into build.js, then run node build.

const {execSync} = require('child_process')

execSync("npm run clean")
execSync("npm run minify")
execSync("npm run build_assets")

It will immediately abort on abnormal npm termination.

Solution 4 - Javascript

The npm documentation recommends using shelljs:

var shell = require("shelljs");

shell.exec("echo shell.exec works");
shell.exec("npm run dev");

See https://blog.npmjs.org/post/118810260230/building-a-simple-command-line-tool-with-npm.html

Solution 5 - Javascript

Use PM2, it is really usefull and easy...

npm install pm2
const pm2 = require('pm2');

pm2.start({
    script: 'npm -- run monitorTheWeather',
    autorestart : false 
  }, (err, apps) => {
    pm2.disconnect()
    if (err) { throw err }
  })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmalcoauriView Question on Stackoverflow
Solution 1 - JavascriptFoysal OsmanyView Answer on Stackoverflow
Solution 2 - JavascriptmzedelerView Answer on Stackoverflow
Solution 3 - Javascriptuser1050755View Answer on Stackoverflow
Solution 4 - Javascriptzr0gravity7View Answer on Stackoverflow
Solution 5 - JavascriptJoris CeelenView Answer on Stackoverflow