Search code examples
node.jsmongodbcronnode-mongodb-native

Will running Node.js scripts as CRON jobs without closing database connection eventually kill all the RAM?


I am building Node.js scripts that will be ran as CRON jobs. (full terminal scripts). These scripts fetch data from all around using APIs and MongoDB (native driver) is used. I don't didn't use db.close() statement and because of that script will never end by itself (or at least it looks like that way from the terminal), to finish it, it is necessary to press CTRL+C to cancel.

Back then when I was writing these scripts, someone from Stack overflow told me that it is not required to close connection anyway. So I let it be.

Now I wonder, do these scripts actually are still running? And as these would be ran as CRON jobs, with small intervals, does that mean that these scripts will eventually kill RAM from the server? Does that mean, there will be thousands scripts running and waiting for db.close() statement?

Example code:

MongoClient.connect(mongoUrl, (err, db) => {
  if (err) {
    console.log(err);
    return;
  }

  var usersCollection = db.collection('users').find();

  usersCollection.on('data', (doc) => {

    console.log(doc);

  });

Solution

  • Node scripts exit by themselves only when nothing listens for events any more.

    With your scripts you probably know when nothing needs to be done after the main purpose of your script is achieved. For example, when the purpose of your script is to execute a certain code, print a summary etc. then you can add process.exit(0); after that command to make sure that the script finishes when it should.

    In the case like this one when you don't have a one line of summary after which you can exit, you can listen for a certain event and exit when when it arrives. For example:

    usersCollection.on('end', process.exit);
    

    In addition to a process.exit in the right spot, you can also set a timeout to terminate the script after a certain time. For example:

    setTimeout(process.exit, 20*1000);
    

    will terminate the script after 20 seconds. This can be added just in case that somethings goes wrong with the database or the connection and you never get the 'end' event, or it takes too long to wait for it.

    Sometimes adding process.exit(0); for scripts like this may be more convenient than closing all the database connections that may be open at that time or other things that may prevent your script from terminating.