Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SailsJS - execute function after "sails lift"

I'm trying to use SailsJS to create a server (with no front-end) that will run some background processes. I was interested in the way SailsJS uses MVC and decided I will give it a try. I created some Models and Controllers, but the thing is that this server is not meant to listen anything. The idea would be to start the server and it should automatically start to run some operations. The problem is that I can't seem to find a way to run some sort of callback after "sails lift".

Maybe I'm making things more complicated with this approach. Do you have any suggestions on how to do it with SailsJs or maybe using another NodeJs alternative / setup?

Thanks.

like image 461
Tony Avatar asked Jun 04 '14 14:06

Tony


People also ask

What does Sails lift do?

Run the Sails app in the current dir (if node_modules/sails exists, it will be used instead of the globally installed Sails). By default, Sails lifts your app in development mode. In the development environment, Sails uses Grunt to keep an eye on your files in /assets .

How do you debug sails?

For Node v6 and above, use sails inspect . Attach the node debugger and lift the Sails app (similar to running node --debug app. js ). You can then use node-inspector to debug your app as it runs.


1 Answers

If you want to run some code when Sails starts, you can use the config/bootstrap.js file, which is a module consisting of a function with a callback argument. From the docs:

module.exports.bootstrap = function (cb) {

  // It's very important to trigger this callback method when you are finished 
  // with the bootstrap!  (otherwise your server will never lift, since it's
  // waiting on the bootstrap)
  cb();
};

As stated in the comment, this happens before the server starts listening for connections, but that is probably fine for you since you don't care about connections anyway.

An alternative in Sails v0.10.x if it's important for your code to execute after Sails lifts and starts listening for connections is to bind a listener for the lifted event in the bootstrap:

module.exports.bootstrap = function (cb) {
  sails.on('lifted', function() {
     // Your post-lift startup code here
  });
  cb();
};
like image 116
sgress454 Avatar answered Oct 17 '22 17:10

sgress454