title: multer: dynamic destination path
body: <p>I am writing a node application and I was looking for something to upload files on the server. I could get files to upload when there was only one static directory. But I need to make directories per user and then upload files to those, according to the user that's logged in. I looked stuff up but everything that I try ends in an Error: ENOENT: no such file or directory, open ... error. What I am trying to do currently is this -</p>
  
  <pre><code>let storage = multer.diskStorage({
    destination: function(req, file, cb) {
      let dest = path.join(__dirname, './documents', 'somenameigetfromtheuser');
      let stat = null;
      try {
        stat = fs.statSync(dest);
      }
      catch (err) {
        fs.mkdirSync(dest);
      }
      if (stat &amp;&amp; !stat.isDirectory()) {
        throw new Error('Directory cannot be created');
      } 
      cb(null, dest);
    }
  });
  
  let upload = multer({
    storage: storage,
    dest: 'documents/'
  });
  
  app.post('/testUpload', upload.single('testfile'), (req, res) =&gt; {
    res.json({
      test: 'test'
    })
  });
  </code></pre>
  
  <p>There is a <a href="https://stackoverflow.com/questions/27213418/node-js-and-multer-handle-the-destination-of-the-uploaded-file-in-callback-fun">similar question</a> that has been answered but it doesn't work that way for me because I want the directory name from the request object.</p>
  
  <p>When I remove the storage property in my multer initialization, the files are stored in the documents directory with a random name. I want the file to have its original name and I want it to be stored in a directory where I get the name of the directory from the req object. <br>
  Help a brother out, thanks!</p>