Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function when an Express server starts up?

I can't seem to figure out how to get my express server to run a simple function when the server starts up. Where is the appropriate place to call a function to run on server startup, and the proper syntax?

I have the function in my routes file as exports.myFunction = function() { code here};

I've tried sticking it in the app.configure block as routes.myFunction. I've tried changing it in routes to just be myfunction() { code}, then calling it in the configure block as routes.myfunction(), no luck there either. The function needs to stay in the file containing my routes since it alters some global variables there.

I know it's some stupidly simple syntax thing, but I can't seem to find any hints here or on google. Much thanks for any help!

like image 795
kjb Avatar asked Mar 20 '12 04:03

kjb


People also ask

What is Express () function?

Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.

Is Express server production ready?

This is an Express. js based Nodejs server that implements production-ready error handling and logging following latest best practices.


1 Answers

Use this event:

app.on('listening', function () {     // server ready to accept connections here }); 

To be honest app returned by express.createServer() is just http.Server, so everything described in nodejs docs related to http.Server make sense for express and railwayjs.

like image 95
Anatoliy Avatar answered Sep 28 '22 15:09

Anatoliy