• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


26 Apr, 2025

Updated at 20 May, 2025

Use hash of content of uploaded file as filename with nodejs and multer

I use multer to upload files to a nestjs backend. The important part of my multer config is

{
    
    // multer options: https://github.com/expressjs/multer#multeropts
    storage: multer.diskStorage({
        filename: async (req, file: Express.Multer.File, cb) => {
            cb(null, await getHashFromStream(file.stream, 'md5'));
        }
    })
}

My getHashFromStream function looks like this

export async function getHashFromStream(stream: Readable, hashAlgo: string): Promise {
    return new Promise((resolve, reject) => {
        const hash = crypto.createHash(hashAlgo);
        stream.on('error', err => reject(err));
        stream.on('data', chunk => hash.update(chunk));
        stream.on('end', () => resolve(hash.digest('hex')));
    });
}

The uploaded file is saved to disk with the right name but the file is empty. I guess this happens as I run through the stream in my getHashFromStream function. When multer wants to run that stream to save the file, it is already done.

My question
What would be an efficient way of solving this? Can I reset the stream? I guess it would be even better if I could calculate the hash while multer is reading the stream to write the file to the disk but I guess the name needs to be known already when the saving starts. At least if I want to use multer as is?!

One obvious solution would be

  • let multer save the file with another name
  • read the file and calculate the hash
  • rename the file

This does not sound very efficient.

Any ideas/suggestions how to solve this?