title: Rename file with user-defined name during upload on Express server
body: <p>I am new to node.js.
  I know this may seem a duplicate question but I looked at many related topics and tried a lot, but this is so complicated...</p>
  
  <p>I use Node.js on server side to upload a file and rename it. the file's new name comes from client side in some hidden field in the form. 
  The problem is that the new name comes in one async function and the file is written in another, so the name is not available when I am writing the file to the stream.</p>
  
  <p>I tried nesting the second call in the callback function of the first, but it didn't fire any more.
  I tried async.waterfall also, but with no success. </p>
  
  <p>Here is the server-side code :</p>
  
  <pre><code>//--------------------------initializing:--------------------------
  var express = require('express');
  var busboy = require('connect-busboy');
  var path = require('path');
  var fs = require('fs-extra');
  var bodyParser = require('body-parser');
  var formidable = require('formidable'); 
  var urlencodedParser = bodyParser.urlencoded({ extended: true }) 
  var app = express();
  
  app.use(bodyParser());
  app.use(busboy());
  app.use(express.static(__dirname ));
  
  app.get('/', function(req, res,next) {
        res.sendFile(__dirname + '/a.html');
  });
  
  var server = app.listen(SERVER_PORT, function() {
      console.log('Listening on port %d', server.address().port);
  });
  
  //------------------Here is the main code : ----------------------
  //UPLOAD is not logged.
  app.post('/upload', function(req, res){
  
      var form = new formidable.IncomingForm();
      var fstream;
      req.pipe(req.busboy);
      var newName ;
      form.parse(req, function(err, fields, files) {  
         newName = fields.hiddenField;
         console.log('PARSE');
         req.busboy.on('file', function (fieldname, file, filename) {
             console.log('UPLOAD');
             fstream = fs.createWriteStream(__dirname + '/img/' + newName + '.jpg');
             file.pipe(fstream);
             fstream.on('close', function () {                 
                 res.redirect('back');   
             });        //where to go next
         });
     });    
  });    
  </code></pre>
  
  <p>Thanks for any help.</p>