Running http-server in background from an npm script
Asked Answered
E

2

33

How do you start http-server in the 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?

The http-server package was installed with:

npm install http-server --save-dev

The package.json file contains:

"scripts": {
   "pretest": "gulp build-httpdocs",
   "test": "http-server -p 7777 httpdocs/ && mocha spec.js"
},

Running npm test successfully starts the http-server, but of course the command hangs after showing:

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?

Bonus: How do you shut down http-server after the Mocha tests have run?

Epicurean answered 19/12, 2017 at 6:32 Comment(4)
check #26457118Rothermere
@IleshPatel That question does not have an accepted answer and it does not apply to npm scripts.Epicurean
are you on linux/mac or on windows?Boden
It would be nice to work on both, but I really only need linux/mac.Epicurean
B
32

You can run a process in background by appending & in the end. And then use the postscript hook that npm offers us, in order to kill the background process.

"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-server running?

You can kill a process by specifying its port in the posttest script:

    "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.

Boden answered 19/12, 2017 at 7:49 Comment(4)
This answer got me there, but I had to make two tweaks (at least for macOS): 1) The http-server command needs to be its own separate npm script because the trailing & must be at the very end AND it causes everything on the line to be run in background and 2) The -f flag is needed to shutdown the web server ("pkill -f http-server")Epicurean
I am glad you got it working! I didn't have linux/mac to test it so I wrote it from memory! Please if you found the solution edit mine or create a new to close it.Boden
Does not work on Win7. It does not put the process in the background. I am trying it with express.Cerberus
The & is not a cross platform solution, which is limits the portability of npm-scriptsGamb
P
4

Probably the cross platform problem can be solved by npm-run-all

Preceptive answered 18/9, 2020 at 22:0 Comment(1)
Yes! run-p --race runHttpServer runTestRabato

© 2022 - 2024 — McMap. All rights reserved.