Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when node.js express server is up and ready to use

Have an application where I want to start a node express server and then start a browser on the same machine automatically as soon as the server is up. How can I query to see if the server is up and ready to go? I really wanted there to be some sort of callback on the .listen call, but doesn't seem to be. I could just wait a longer than I expect amount of time, but this is going on equipment that will be in the field so I either have to wait a ridiculous amount of time to make sure I'm up and running before kicking off the browser or have the user be smart enough to hit refresh if the page doesn't load right. Neither of those are good options for me. . .

I read the API online but don't see anything like this. Surely there's a trick I don't know that can accomplish this.

If the node HTTP api (which has a callback and tells me about the listening event) is the base for the express object, maybe there is a callback option for the express call listen that isn't documented. Or perhaps I'm supposed to just know that it's there.

Any help would be greatly appreciated.

like image 459
Brian Avatar asked Aug 14 '13 20:08

Brian


1 Answers

The Express app.listen function does support a callback. It maps the arguments that you pass in to the http.listen call.

app.listen = function(){   var server = http.createServer(this);   return server.listen.apply(server, arguments); }; 

So you can just call: app.listen(port, callback);

Or you could use http.listen directly.

var app = require('express')(),     server = require('http').createServer(app);  server.listen(80, function() {     console.log('ready to go!'); }); 
like image 133
Timothy Strimple Avatar answered Sep 22 '22 10:09

Timothy Strimple