prevent NodeJS program from exiting

Viewed 16707

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!

3 Answers

You can begin reading from the process' standard input:

import process from 'process';

process.stdin.resume();

// do your thing

This will prevent the process from immediate termination.

This is mentioned in the official documentation.

However, this could prevent your process from being gracefully killed.

Building off @jfriend00's answer I did this, so it's killable

var running = true;

function killProcess() {
    running = false;
}

process.on('SIGTERM', killProcess);
process.on('SIGINT', killProcess);
process.on('uncaughtException', function(e) {
    console.log('[uncaughtException] app will be terminated: ', e.stack);
    killProcess();
});

function run() {
    setTimeout(function() {
        if (running) run();
    }, 10);
}

run();
Related