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?

4

2 Answers 2

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.

4
  • 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") Commented Dec 20, 2017 at 3: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. Commented Dec 20, 2017 at 6:36
  • 1
    Does not work on Win7. It does not put the process in the background. I am trying it with express.
    – inf3rno
    Commented Oct 2, 2018 at 17:14
  • 2
    The & is not a cross platform solution, which is limits the portability of npm-scripts Commented May 4, 2019 at 18:08
4

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

1
  • Yes! run-p --race runHttpServer runTest
    – atablash
    Commented Feb 22, 2022 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.