nicholaswmin
nicholaswmin

Reputation: 22939

Start node server via shell and print something when done

I'm looking for a way to start a Node server via a shell command and print something afterwards.

tl;dr

I have a Gulp task that:

Now, for the callback to fire properly there are 2 solutions I can use:

Solution 1

Example server/app.js:

http.listen((process.env.PORT || 5000), function(){
  console.log("start");
});

This solution is not ideal.

Solution 2

Example:

$ node server.app.js && echo 'start'

This is the ideal since it doesn't couple what my app.js file is printing with my gulpfile.js.

The above doesn't work - when running it, it just outputs what my server has configured to be printing on startup. The 'start' string never get's printed.

The gulptask

gulp.task("node server/app.js && echo 'start'", function(cb) {

  serverProcess.stdout.on("data", function(data) {
    if(data.toLowerCase().includes("start")) {
      return cb();
    }
  });
});

The above task of course won't work but it's a good ballpark of what I'm trying to achieve.

Upvotes: 1

Views: 357

Answers (2)

Samuel Rossille
Samuel Rossille

Reputation: 19838

The problem with $ node server/app.js && echo 'start' is that whatever is after && will only run after the server process has finished running, not after it has started.

What you want is to run something after the server has started.

You can achieve this with something like that $ node server/app.js & sleep 2 && echo 'start' (sleep because you want to give it some time to actually connect to actually start before saying it has started)

Note: I think it's quite conventional to say that the server is listening on port XXXX in the log of a server.

Upvotes: 1

TN1ck
TN1ck

Reputation: 691

There isn't a real solution for this, because the node application is blocking, you will never now when it started without using some clues from the application itself. The one thing that you could do that would work without outputting a string from the server, is checking if the node application is listening on its port. Something like netstat -ant | awk '$6 == "LISTEN" && $4 ~ /\.4000$/' where the 4000 is the port on which the node-app is listening.

But I would recommend that you keep your first approach, the coupling isn't such a big deal in my opinion.

Upvotes: 1

Related Questions