javascript - 从 npm 脚本在后台运行 http-server

标签 javascript node.js npm background-process httpserver

如何从 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/

相关文章:

javascript - 多选 jQuery-Dropdown 插件

javascript - 用于获取用户输入并将其传递给批处理文件的 GUI

javascript - 无法使用 npm 5.6.0 安装 cordova

javascript - Node js模块如何获取导出函数列表

node.js - npm sudo 全局安装 & unsafe-perm

node.js - Nodejs 的依赖管理不仅控制模块的版本,还控制 npm 和 Node 本身的版本

javascript - 使用 jquery 或 PHP 捕获当前屏幕的正确图像或将 div 转换为 pdf

javascript - OOP Jquery 由于闭包而丢失值

javascript - Node.js setImmediate 在 I/O 回调之前执行(事件循环)

node.js - Windows 上的 Node-gyp 5 : Cannot find npm\node_modules\node-gyp\bin\node-gyp. js