title: How can I rename a file in node.js?
body: <p>I'm trying to implement a file upload form using angular and node. The files upload fine, but I want to scan the upload directory to see if the filename already exists. If so, then the file would be renamed. Here is what I have so far:</p>
  
  <pre><code>app.post('/file', function(req, res) {
      var fs = require('fs');
      var file = req.files.file;
  
      // destination directory
      var dest_dir = './uploads;
      var filename = file.name;
  
      // THIS ISN'T WORKING, I.E., THE FILE IS NOT RENAMED
      fs.readdir(dest_dir, function(err, dir_files) {
          for(var i = 0; i &lt; dir_files.length; i++) {
              if(dir_files[i] == filename) {
                  console.log("I can see this message, but the file isn't renamed");
                  filename = filename + '_1'; // rename the file
              }
          }
      });
  
      // read file from temp dir and store in permanent dir
      var source = fs.createReadStream(file.path);
      var dest = fs.createWriteStream(dest_dir + '/' + filename);
      source.pipe(dest);
  
      source.on('end', function() { res.json("File has been uploaded!") });
      source.on('error', function(err) { res.json("There was an error when attempting to upload this file.") });
  });
  </code></pre>
  
  <p>What am I doing wrong?</p>