【问题标题】:Running http-server in background from an npm script从 npm 脚本在后台运行 http-server
【发布时间】:2021-12-12 11:16:48
【问题描述】:

如何从 npm 脚本在后台启动 http-server,以便另一个 npm 脚本(例如 Mocha test using jsdom)可以向http-server?

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

【问题讨论】:

  • @IleshPatel 这个问题没有被接受的答案,它不适用于 npm 脚本。
  • 你是在linux/mac还是windows上?
  • 两者都可以,但我真的只需要 linux/mac。

标签: javascript node.js npm background-process httpserver


【解决方案1】:

您可以通过在末尾附加& 在后台运行进程。 然后使用 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 不支持多个操作系统脚本。为了支持多个,我最好的选择是处理每个操作系统不同的 gulp 任务。

【讨论】:

  • 这个答案让我到达了那里,但我必须做两个调整(至少对于 macOS):1) http-server 命令需要成为自己单独的 npm 脚本,因为尾随 & 必须在最后,并且它会导致行上的所有内容都在后台运行,并且 2) 需要关闭 -f 标志网络服务器 ("pkill -f http-server")
  • 我很高兴你能成功!我没有 linux/mac 来测试它,所以我是凭记忆写的!如果您找到了解决方案,请编辑我的解决方案或创建一个新解决方案来关闭它。
  • 不适用于 Win7。它不会将进程置于后台。我正在尝试使用 express。
  • & 不是跨平台解决方案,这限制了 npm-scripts 的可移植性
【解决方案2】:

跨平台问题大概可以npm-run-all解决

【讨论】:

  • 是的! run-p --race runHttpServer runTest
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多