javascript 从 npm 脚本在后台运行 http-server
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47881223/
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
Running http-server in background from an npm script
提问by Dem Pilafian
How do you start http-serverin background from an npm script so that another npm script, such as a Mocha test using jsdom, can make an HTTP request to http-server?
您如何http-server从 npm 脚本在后台启动,以便另一个 npm 脚本(例如使用 jsdom的Mocha 测试)可以向 发出 HTTP 请求http-server?
The http-serverpackage was installed with:
该http-server软件包已安装:
npm install http-server --save-dev
The package.jsonfile contains:
该package.json文件包含:
"scripts": {
"pretest": "gulp build-httpdocs",
"test": "http-server -p 7777 httpdocs/ && mocha spec.js"
},
Running npm testsuccessfully starts the http-server, but of course the command hangs after showing:
运行npm test成功启动http-server,但当然显示后命令挂起:
Starting up http-server, serving httpdocs/
Available on:
http://127.0.0.1:7777
http://192.168.1.64:7777
Hit CTRL-C to stop the server
Is there an easy way to start the web server so it does not block the Mocha tests?
有没有一种简单的方法来启动 Web 服务器,这样它就不会阻止 Mocha 测试?
Bonus:How do you shut down http-serverafter the Mocha tests have run?
奖励:http-server在 Mocha 测试运行后,您如何关闭?
采纳答案by Alex Michailidis
You can run a process in background by appending &in the end.
And then use the postscripthook that npm offers us, in order to kill the background process.
您可以通过&在末尾附加来在后台运行进程。然后使用postscriptnpm 为我们提供的钩子,以杀死后台进程。
"scripts": {
"web-server": "http-server -p 7777 httpdocs &",
"pretest": "gulp build-httpdocs && npm run web-server",
"test": "mocha spec.js",
"posttest": "pkill -f http-server"
}
But what if I have multiple http-serverrunning?
但是如果我有多个http-server跑步呢?
You can kill a process by specifying its port in the posttestscript:
您可以通过在posttest脚本中指定其端口来终止进程:
"posttest": "kill $(lsof -t -i:7777)"
Now for Windows, syntax is different and as far as I know npm doesn't support multiple OS scripts. For supporting multiple my best bet would be a gulp task that will handle each OS different.
现在对于 Windows,语法是不同的,据我所知 npm 不支持多个操作系统脚本。为了支持多个我最好的选择是一个吞咽任务,它将处理每个不同的操作系统。

