admin管理员组文章数量:1402181
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
本文标签: javascriptNodejs Run a js file on node server startupStack Overflow
版权声明:本文标题:javascript - Nodejs: Run a js file on node server startup - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744268625a2598069.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论