prevent NodeJS program from exiting

你离开我真会死。 提交于 2019-12-06 00:26:08

问题


I am creating NodeJS based crawler, which is working with node-cron package and I need to prevent entry script from exiting since application should run forever as cron and will execute crawlers at certain periods with logs.

In the web application, server will listen and will prevent from terminating, but in serverless apps, it will exit the program after all code is executed and won't wait for crons.

Should I write while(true) loop for that? What is best practices in node for this purpose?

Thanks in advance!


回答1:


Because nodejs is single thread a while(true) will not work. It will just grab the whole CPU and nothing else can ever run.

nodejs will stay running when anything is alive that could run in the future. This includes open TCP sockets, listening servers, timers, etc...

To answer more specifically, we need to see your code and see how it is using node-cron, but you could keep your nodejs process running by just adding a simple setInterval() such as this:

setInterval(function() {
    console.log("timer that keeps nodejs processing running");
}, 1000 * 60 * 60);

But, node-cron itself uses timers so it appears that if you are using node-cron properly and you correctly have tasks scheduled to run in the future, then your nodejs process should not stop. So, I suspect that your real problem is that you aren't correctly scheduling a task for the future with node-cron. We could help you with that issue only if you show us your actual code that uses node-cron.




回答2:


I think the best way to prevent exit from process is:

process.stdin.resume();

I found this solution here https://stackoverflow.com/a/14032965/2094090 and it works fine.



来源:https://stackoverflow.com/questions/44137481/prevent-nodejs-program-from-exiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!