title: What is a good way to exit a node.js script after "everything has been done"
body: <p>My node.js script reads rows from a table in database 1, does some processing and writes the rows to database 2.</p>
  
  <p>The script should exit after everything is done.</p>
  
  <p>How can I know if everything has been done and exit node then?</p>
  
  <p>If I have a callback function like this:</p>
  
  <pre><code>function exit_node() {
    process.exit();
  }
  </code></pre>
  
  <p>(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.)</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>It could also theoretically happen, that the last write finished, but another write before that is still executing.</p>
  
  <hr>
  
  <p>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.</p>
  
  <hr>
  
  <p>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: <a href="https://github.com/caolan/async" rel="noreferrer">https://github.com/caolan/async</a> </p>
  
  <p>I also fear this would blow up the code and the logic unreasonable.</p>