Javascript 如何以编程方式执行“npm run”命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38032047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:00:03  来源:igfitidea点击:

How to execute 'npm run' command programmatically?

javascriptnode.js

提问by malcoauri

I have some custom testing script, which I can run with npm run testcommand, 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 devmanually executing and move it to custom npm run testscript, i.e. I want to execute webpack dev server programmatically in Node script. How can I execute npm run devprogrammatically using Node script and stop it then? Thanks in advance!

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

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

回答by Foysal Osmany

You can use exec to run from script

您可以使用 exec 从脚本运行

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

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

回答by mzedeler

Just install npm:

只需安装npm

npm install npm

Then in your program:

然后在你的程序中:

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

See the source for more info. The npm.commandobject is an unofficial API for npm.

有关更多信息,请参阅来源。该npm.command对象是 npm 的非官方 API。

回答by Joris Ceelen

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

使用PM2,它真的有用且简单...

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

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