Is multer's sole purpose to add a body object and files object to the request object? Should editing and saving be done by different package?

Viewed 397

I'm trying to figure out how file uploading and processing works in Node.js and I'm not sure what is multer's responsibility in that matter. Is multer's sole purpose to add a body object and files object to the request object? Should editing and saving the file to the file system be done by different package?

While I can see that I can set up multer to automatically save the file in the files object, it seems that the options are very limited and image processing is out of multer's scope. Does that mean I need another package that specifically handles image processing?

Would that package take the file stream buffer from the files object and make it into an actual file, then apply all the changes to it?

1 Answers

multer is just a middleware to handle data from request with multipart/form-data header, and you can't do image processing with that, although there are few packages that integrate image processing library with multer like multer-sharp or multer-sharp-s3 (for uploading to S3 bucket).

Is multer's sole purpose to add a body object and files object to the request object?

That, and also where you want to store the file (multer storage)

Does that mean I need another package that specifically handles image processing?

Yes, multer alone can't do any image processing as I mentioned above. You can use something like sharp to do image processing.

Would that package take the file stream buffer from the files object and make it into an actual file, then apply all the changes to it?

Yes, for example using sharp library:

router.post('/upload',upload.single('image') ,async (req, res) => {
   const { filename: image } = req.file 

   await sharp(req.file.path)
    .resize(500)
    .jpeg({quality: 50})
    .toFile(
        path.resolve(req.file.destination,'resized',image)
    )
    fs.unlinkSync(req.file.path)

    return res.send('SUCCESS!')
})

Example is taken from this dev.to article

Related