如何在npm脚本的后台启动http-server
,以便另一个npm脚本(如Mocha test using jsdom)可以向http-server
发出HTTP请求?
http-server
软件包安装有:
npm install http-server --save-dev
package.json
文件包含:
"scripts": {
"pretest": "gulp build-httpdocs",
"test": "http-server -p 7777 httpdocs/ && mocha spec.js"
},
运行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
是否有一种简单的方法来启动Web服务器,因此它不会阻止Mocha测试?
额外奖励:在摩卡测试结束后你如何关闭http-server
?
您可以通过在最后添加&
来在后台运行流程。然后使用npm为我们提供的postscript
钩子,以便杀死后台进程。
"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"
}
但是,如果我有多个http-server
运行怎么办?
您可以通过在posttest
脚本中指定其端口来终止进程:
"posttest": "kill $(lsof -t -i:7777)"
现在对于Windows,语法是不同的,据我所知,npm不支持多个OS脚本。为了支持多个我最好的选择将是一个gulp任务,将处理每个操作系统不同。