Running http-server in background from an npm script

Dem Pilafian picture Dem Pilafian · Dec 19, 2017 · Viewed 12.4k times · Source

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

Answer

Alex Michailidis picture Alex Michailidis · Dec 19, 2017

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.