关于javascript:如何以编程方式执行“ npm run”命令?

How to execute 'npm run' command programmatically?

我有一些自定义测试脚本,可以使用npm run test命令运行该命令,该命令执行一些Node脚本以启动e2e /单元测试。 但是在此之前,我必须在其他终端窗口中使用npm run dev(也是一些自定义Node脚本,细节无关紧要)启动webpack开发服务器。 因此,我想省略手动执行的npm run dev并将其移到自定义的npm run test脚本中,即我想在Node脚本中以编程方式执行webpack开发服务器。 如何使用Node脚本以编程方式执行npm run dev并随后将其停止? 提前致谢!

1
"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"


您可以使用exec从脚本运行

1
2
3
4
5
6
7
import {series} from 'async';
const {exec} = require('child_process');

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


只需安装npm

1
npm install npm

然后在您的程序中:

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

请参阅源以获取更多信息。 npm.command对象是npm的非官方API。


使用PM2,它确实非常有用且容易...

1
npm install pm2
1
2
3
4
5
6
7
8
9
const pm2 = require('pm2');

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