3

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?

3
  • Just make them node.js modules and load these other things into you main app with require(). You can then run them as needed. Commented Apr 11, 2016 at 6:10
  • use cronjob, it would help Commented Apr 11, 2016 at 6:12
  • Making the them as node modules and use worked...Thanks Commented Apr 11, 2016 at 8:32

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what i was looking for. Thanks...!
1

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

1 Comment

Exact solution was to use them as node modules... Anyways, +1 for the init approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.