Prashant soni
Prashant soni

Reputation: 85

Nodejs: Run a js file on node server startup

I have some piece of nodejs code (scheduler and few db queries) that i want to run each time along with rest of the app (Express App) when the node server is started.
One way which i can think of is creating a batch file which will have 2 lines: one to start the node server and the other to run that node js code (Haven't tested this approach though).

I was thinking if there could be a way to execute that static code via server.js file. I want to run this with in same instance.
Any help here?

Upvotes: 3

Views: 7491

Answers (2)

Nalla Srinivas
Nalla Srinivas

Reputation: 933

You have to create two modules for scheduler and database queries to execute them when ever node started. In your main file import those modules and initialize the startup process like scheduling and db queries.

for example: Main file is Server.js

 var scheduler=require("/utils/schedular.js");
     scheduler.init();

Now your scheduler.js file should be as below:

 var schedular=function(){

var _self=this;

 _self.init=function(){
    console.log("init Schedular");
    var rule = new cron.RecurrenceRule();
    rule.second = 30;
    cron.scheduleJob(rule, function(){
          console.log(new Date(), 'The 30th second of the minute.');
            // write your logic


          });
    });
  }
 }

  module.exports=new scheduler();

As like thins you have create another file for executing the db queries. when ever your main file runs using node or forever then your scheduler and db queries also will execute

Upvotes: 1

metarmask
metarmask

Reputation: 1857

You can execute other scripts in the same directory by adding require() functions to your server.js file:

var exportedThings = require("./path/to/file.js");

In file.js you can assign values to the exports object to export them to requiring scripts:

exports.add = function(first,second){
    return first + second;
}

Now, in server.js you will be able to:

exportedThings.add(1, 5); // Outputs 6

Upvotes: 4

Related Questions