Nicholas Kyriakides Nicholas Kyriakides - 1 year ago 55
Bash Question

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.


I have a Gulp task that:

  • Starts a node server by issuing a
    $ node server/app.js

  • Must call a callback
    after the server has started up.

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

Solution 1

  • Have the server output something after startup


http.listen((process.env.PORT || 5000), function(){

This solution is not ideal.

  • It introduces coupling between the gulpfile.js and server/app.js.

  • The coupling is that 'start' keyword.

Solution 2

  • Issue an
    $ echo
    command when issuing a
    $ node server/app.js


$ node && echo 'start'

This is the ideal since it doesn't couple what my
file is printing with my

The above doesn't work - when running it, it just outputs what my server has configured to be printing on startup. The
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download