multer中的cb是什么?

What is cb in multer?

在下面的代码中,来自多个 API,目标和文件名选项都是匿名函数。这两个函数都有一个名为 cb 的参数。这些回调函数是在 multer 模块的某个地方定义的还是我应该提供它们?

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 }

简答:您提供回调。

cb是一个接受2个参数的回调函数。

您可以在任一方法的使用场景中看到这一点。比如...

let req = true;
let file = 'MyFile.txt';
function myCallbackFunc = function(value1, value2){ console.log('my callback function'); };
storage.filename(req, file, myCallbackFunc));

请理解,我不知道 "req" 或 "file" 参数应该是什么样子,所以我只是为示例编造了一些东西。

注:我不知道multer是什么

假设你有一个函数,

 function destination(req, files){
    //something happen here
 }

现在在你的代码中你用两个参数调用这个函数

destination(req, files);

而现在如果你需要在完成上述功能后立即执行另一个功能,你需要有一个回调函数。 假设您需要 console.log('Hello world') 在目标函数完成后,

destination(req, files , function(){
    console.log('hello world')
});

我相信你知道这种功能。现在的问题是目标函数只接受 2 个参数,所以我们需要在函数定义中添加另一个参数。让我们将第三个参数称为 'cb'

 function destination(req, files, cb){
    //something happen here
 }

现在cb的类型应该是什么?它应该是一个函数。不是吗? 所以如果第三个参数是一个函数,那么我们必须在某个地方执行这个 cb 函数。执行 cb 函数的最佳位置是在目标函数内的所有代码之后。

 function destination(req, files, cb){
    //something happen here
    cb();
 }

这里我们有一个回调函数!!如果你深入思考,你就会明白为什么他们引入了 javaScript Promises

答案是:是的,cb是multer提供的。是的,奇怪的文档对此只字未提。

此回调是所谓的错误优先函数,因此在检查 reqfile 时,您可能会决定,该用户上传了错误的内容,通过new Error() 作为第一个参数,它将作为响应返回。但请注意,它会在您的应用程序中引发未处理的异常。所以我更喜欢始终传递 null 并在相应的控制器中处理用户输入。

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
});