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?
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?
-
Just make them node.js modules and load these other things into you main app with
require()
. You can then run them as needed. – jfriend00 Commented Apr 11, 2016 at 6:10 -
use
cronjob
, it would help – Oki Erie Rinaldi Commented Apr 11, 2016 at 6:12 - Making the them as node modules and use worked...Thanks – Prashant soni Commented Apr 11, 2016 at 8:32
2 Answers
Reset to default 4You 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
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