Maxim Velichkin Maxim Velichkin - 1 year ago 36
JSON Question

The command does not work until the http server is turned off

I have a "server" folder in which I installed a npm package.json file and http server, and there is also a "webdir" folder with a web page (inside the "server" folder).

I wrote a command

npm start
in npm package.json file, that makes 3 things:

  1. Go to the folder with the web page:
    cd webdir

  2. Start the http server :
    node ../node_modules/http-server/bin/http-server

  3. Open a web page:
    open http:localhost:8080

Final code:

"start": "cd webdir && node ../node_modules/http-server/bin/http-server && open http:localhost:8080"

I encountered a problem: if I write these three commands in sequence in package.json file using && or semicolon, the third command is not executed until I manually stop the server. Apparently the command to start the server remains incomplete until the server is turned off.

How can I avoid it?

I work on Imac (Mac OS EL Capitan)

Answer Source

The issue is that http-server will run indefinitely, until you (manually) stop it. Only after it has stopped will the following command (open ...) be executed, which is too late.

A solution is to start the HTTP server in the background. Because this may cause problems (the HTTP server will keep running even after npm exits), you have to also wait for its exit using the shell's wait command:

"start": "cd webdir && node ../node_modules/http-server/bin/http-server & open http://localhost:8080 ; wait"

Notice that between http-server and open is a single ampersand. This backgrounds the http-server process.

Depending on how fast the server starts, you may still get an error page in the browser (when the browser requests the page before the server has fully started). To work around this, you need to add a sleep 3; (meaning "sleep 3 seconds") between the single ampersand and open:

cd webdir && node ../node_modules/http-server/bin/http-server & sleep 3; open http:localhost:8080 ; wait