32

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?

Dem Pilafian
  • 5,625
  • 6
  • 39
  • 67

2 Answers2

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.

Alex Michailidis
  • 4,078
  • 1
  • 16
  • 35
  • 2
    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"`) – Dem Pilafian Dec 20 '17 at 03:57
  • 1
    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. – Alex Michailidis Dec 20 '17 at 06:36
  • 1
    Does not work on Win7. It does not put the process in the background. I am trying it with express. – inf3rno Oct 02 '18 at 17:14
  • 2
    The `&` is not a cross platform solution, which is limits the portability of npm-scripts – deepelement May 04 '19 at 18:08
4

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