Search code examples
javascriptnode.jsnpmmulter

Multer Unique Filename


I had a doubt about Multer Filename.

When a multer stores the file with a random fileName then, can there be a case where two files have the same name in multer?

Basically what I want to say is If I am storing file from large numbers of users, can the filename get repeated? Can I trust multer on this or do I have to write a separate function to give a unique filename to each file?


Solution

  • From the npm page here, we can see Multer's example code to store a file on disk :

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, '/tmp/my-uploads')
      },
      filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
      }
    })
     
    var upload = multer({ storage: storage })
    

    The filename is concatenated with '-' + Date.now(). Date.now() give you the number of milliseconds from 1st January 1970. So, if 2 files are saved at different times, they have different names. And theoretically, if 2 files are saved on the system at exactly the same time (milliseconds unit) they will have the same name.

    So, it does not depend on how many files you store but how fast requests come to your system. If you have more than 1000 requests per second, there will be a chance for duplication. In this case, you should use something like UUID. Otherwise, Date.now() does the work.

    • You can read more about Date.now()here.
    • Wikipedia page about UUID here, in case you need it. It also has a npm package.