Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to exit a node.js script after "everything has been done"

My node.js script reads rows from a table in database 1, does some processing and writes the rows to database 2.

The script should exit after everything is done.

How can I know if everything has been done and exit node then?

If I have a callback function like this:

function exit_node() {
  process.exit();
}

(Edit: in the meantime it became obvious that process.exit() could be also replaced with db.close() - but this is not the question what to put in there. The question is at which time exactly to do this, i.e. how and where to execute this callback.)

But it is not easy to attach it somewhere. After the last read from db1 is not correct, because the processing and writing still has to happen.

Attaching it to the write to db2 is not easy, because it has to be attached after the last write, but each write is indepenent and does not know if it is the last write.

It could also theoretically happen, that the last write finished, but another write before that is still executing.


Edit: Sorry, I can see the explanation of the question is not complete and probably confusing, but some people still understood and there are good answers below. Please continue reading the comments and the answers and it should give you the whole picture.


Edit: I could think of some "blocking" controller mechanism. The different parts of the script add blockers to the controller for each open "job" and release them after the job is finished, and the controller exits the script when no more bockers are present. Maybe async could help: https://github.com/caolan/async

I also fear this would blow up the code and the logic unreasonable.

like image 755
SHernandez Avatar asked Jun 03 '12 17:06

SHernandez


2 Answers

JohnnyHK gives good advice; except Node.js already does option 2 for you.

When there is no more i/o, timers, intervals, etc. (no more work expected), the process will exit. If your program does not automatically exit after all its work is done, then you have a bug. Perhaps you forgot to close a DB connection, or to clearTimeout() or clearInterval(). But instead of calling process.exit() you might take this opportunity to identify your leak.

like image 69
JasonSmith Avatar answered Sep 24 '22 04:09

JasonSmith


The two main options are:

  1. Use an asynchronous processing coordination module like async (as you mentioned).
  2. Keep your own count of outstanding writes and then exit when the count count reaches 0.
like image 22
JohnnyHK Avatar answered Sep 24 '22 04:09

JohnnyHK