如何从 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 测试?
奖励:在 Mocha 测试运行后如何关闭 http-server
?
最佳答案
您可以通过在末尾附加 &
来在后台运行进程。
然后使用 npm 提供给我们的 postscript
钩子(Hook),以杀死后台进程。
"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 不支持多个操作系统脚本。为了支持多个,我最好的选择是处理每个操作系统不同的 gulp 任务。
关于javascript - 从 npm 脚本在后台运行 http-server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47881223/