title: How to exit properly from node.js
body: <p>The following will read and import many CSV files from disk into MongoDB but NodeJS won't exit after importing all the files if it doesn't go through the resizePhoto() function (Which contains a process.exit after resizing the images).</p>
  
  <p>How can I have it to close properly after importing all files without interrupting? If I add a process.exit .on end it will exit after importing the first file.</p>
  
  <pre><code>var importData = function(fileName) {
  
      // Get file from disk.
      var filePath = path.join(folder, fileName);
  
      // Read and import the CSV file.
      csv.fromPath(filePath, {
          objectMode: true,
          headers: keys
      })
      .on('data', function (data) {
  
          var Obj = new models[fileName](data);
  
          models[fileName].find({}).remove().exec();
  
          Obj.save(function (err, importedObj) {
              if (err) {
                  console.log(fileName, err);
              } else if (fileName === 'PHOTOS') {
                  resizePhoto(importedObj);
              }
          });
  
      })
      .on('end', function() {
          console.log(fileName + ': Imported.');
      });
  };
  
  module.exports = importData;
  </code></pre>