Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is cb in multer?

In the code below, from the multer API, both the destination and filename options are anonymous functions. Both of these functions have an argument called cb. Are these callback functions defined in the multer module somewhere or am I supposed to supply them?

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 }
like image 582
user3425506 Avatar asked Apr 30 '19 16:04

user3425506


1 Answers

The answer is: yes cb is provided by multer. And yes, it's weird documentation says nothing about it.

This callback is a so called error-first function, thus when examining the req, or file you may decide, that user uploaded something wrong, pass new Error() as first argument, and it will be returned in response. Note though, that it will raise an unhandled exception in your app. So I prefer to always pass null and handle user input in the corresponding controller.

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const error = file.mimetype === 'image/jpeg'
      ? null
      : new Error('wrong file');
    cb(error, '/if-no-error-upload-file-to-this-directory');
  },
  //same for filename
});
like image 196
fires3as0n Avatar answered Sep 25 '22 13:09

fires3as0n