Dem Pilafian
Dem Pilafian

Reputation: 5986

Running http-server in background from an npm script

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?

Upvotes: 33

Views: 23748

Answers (2)

Camila Belo
Camila Belo

Reputation: 41

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

Upvotes: 4

Alex Michailidis
Alex Michailidis

Reputation: 4143

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.

Upvotes: 33

Related Questions