title: Can't send headers after they are sent. File upload, async issue?
body: <p>I am developing a multiple file upload feature using ajax, nodejs, express and the module formidable.</p>
  
  <p>However I am sometimes getting the error <code>Can't set headers after they are sent.</code>, from the error stack trace, it's because of the line <code>return res.send({ status: 'success', files: files['upload']</code> </p>
  
  <p>I tried to review what could make it be sent more than once, and I included a counter to make sure it would be fired one time once all files were uploaded, but the error still happens sometimes.</p>
  
  <pre><code>var express     = require('express'),
      router      = express.Router(),
      formidable  = require('formidable'),
      util        = require('util'),
      fs          = require('fs'),
      form        = new formidable.IncomingForm(),
      path        = require('path'),
      nodeHomeDir = path.dirname(require.main.filename);
  
  form.type = 'multipart';
  form.multiples = true;
  form.maxFieldsSize = 52428800;
  form.uploadDir = nodeHomeDir + '/tmp';
  form.keepExtensions = true;
  
  /* POST to /files to upload or delete files */
  router.post('/', function (req, res, next) {
  
    form.parse(req, function (err, fields, files) {
      if (!files['upload'][0]) return res.send({ status: 'fail', message: 'No files provided.' });
  
      req.on('aborted', function () {
        return res.send({ message: 'fail' });
      });
  
      var webinarID     = fields.webinarID,
          uploadDirName = nodeHomeDir + '/webinarFiles/' + webinarID,
          filesLength   = Object.keys(files['upload']).length,
          counter       = 0;
  
      if (!webinarID) return res.send({ status: 'fail', message: 'No webinar ID provided.' });
  
      if (!fs.existsSync(uploadDirName)) {
        fs.mkdirSync(uploadDirName);
      }
  
      for (file in files['upload']) {
        if (files['upload'][file] &amp;&amp; files['upload'][file].path &amp;&amp; files['upload'][file].name) {
          var stream = fs.createReadStream(files['upload'][file].path).pipe(fs.createWriteStream(uploadDirName + '/' + files['upload'][file].name));
          stream.on('finish', function () {
            counter++;
            if (counter === filesLength) {
              // deleteFilesFromFolder(nodeHomeDir + '/tmp');
              return res.send({ status: 'success', files: files['upload'] });
            }
          });
        }
      }
  
    });
  
  });
  </code></pre>