为什么这段代码可以作为中间件而不是函数?

时间:2016-10-17 10:56:30

标签: javascript node.js module

如果在此问题中启动此代码,则此代码可以正常工作:

app.route('/upload').post(rulesUpload.upload(obj),function (request, response, next) {
    response.status(200).end('File Caricato/i Con Successo');
});

而不是如果我写:

app.route('/upload').post(function(request, response, next) {
  rulesUpload.upload(obj);
  response.status(200).end('File Caricato/i Con Successo');
});


var  formidable  =  require('formidable'),
      util  =  require('util'),
      fs    =  require('fs-extra');
var defaultMaxSize = 3;
var defaultMaxFiles = 1;

exports.upload = function(obj) {
  return function(req, res, cb) {
    var check = '';
    var errors = {};
    for (key in req.files) {
      if ((obj.required != undefined && req.files[key].size == 0) && (obj.required[key] != undefined && obj.required[key]))
        check = "Il file " + key + " è obbligatorio!";
      else if (obj.destination[key] == undefined)
        check = 'Il file ' + key + ' non è gestito correttamente.';
      else if (obj.files[key] != undefined && obj.files[key] < req.files[key].length)
        check = 'Non si possono inserire più di ' + obj.files[key] + ' file per il campo ' + key;
      else if (obj.files[key] == undefined && defaultMaxFiles < req.files[key].length)
        check = 'Non si possono inserire più di ' + defaultMaxFiles + ' file per il campo ' + key;
      else {                
        var  new_location  =  obj.destination[key] + '/';
        var numFiles = 1;
        if (req.files[key].length != undefined)
          numFiles = req.files[key].length;
        if (numFiles == 1)
          req.files[key] = {
            0: req.files[key]
          };

                    
        for (var  i  =  0;  i  < numFiles;  i++)  {                
          var  file_name  = '';
          if (obj.filename[key] != undefined) {
            file_name = obj.filename[key].name;
            if (file_name == undefined)
              file_name = req.files[key][i].name.substring(0, req.files[key][i].name.lastIndexOf("."));
            if (obj.filename[key].prefix != undefined)
              file_name = obj.filename[key].prefix + file_name;
            if (obj.filename[key].suffix != undefined)
              file_name += obj.filename[key].suffix;
            file_name += req.files[key][i].name.substring(req.files[key][i].name.lastIndexOf('.'), req.files[key][i].name.length);
          } else file_name = req.files[key][i].name;
          if (obj.fileTypes[key] != undefined) {
            var re = new RegExp(obj.fileTypes[key]);
            var mimetype = re.test(req.files[key][i].type);
            var extname = re.test(req.files[key][i].name.toLowerCase());
            if (!mimetype && !extname)
              check = "Sono Accettate solo le seguenti estensioni: " + obj.fileTypes[key] + " per il campo " + key;
          }
          if (obj.fileSize[key] != undefined && req.files[key][i].size > obj.fileSize[key] * 1024 * 1024)
            check = 'I file ' + key + ' non possono superare i ' + obj.fileSize[key] + " MB";
          if (obj.fileSize[key] == undefined && req.files[key][i].size > defaultMaxSize * 1024 * 1024)
            check = 'I file ' + key + ' non possono superare di default i ' + defaultMaxSize + " MB";
          if (check == '') {                
            var  temp_path  =  req.files[key][i].path;

                            
            fs.move(temp_path,  new_location  +  file_name,  function (err)  {                    
              if  (err)  {                    } 
              else  {                    }                
            });
          } else {
            errors[key] = check;
          }
          if (check != "")
            errors[key] = check;

        }
        if (check != "")
          errors[key] = check;
      }
      if (check != "")
        errors[key] = check;
      check = '';            
    }
    if (check != "")
      errors[key] = check;
    check = '';
    if (errors != {})
      return cb(util.inspect(errors));
    else return cb(null);        
  };
  return;
};

P.S。:对于超级用户,我知道返回阶段存在错误,但我没有找到任何解决方案,这是次要问题。

P.S.2:对于好奇的人,我使用这段代码来检查发送的文件是否可以上传。

2 个答案:

答案 0 :(得分:1)

因为您将上传称为同步功能,但由于fs.move它是异步的。此外,您的呼叫返回一个功能。 只需将回调传递给您的函数并将其调用如下:

rulesUpload.upload(obj, function(){
 response.status(200).end('File Caricato/i Con Successo');
})

将原型更改为:

exports.upload = function(obj, cb) {
 // return function(req, res, cb) { // REMOVE THIS LINE

答案 1 :(得分:1)

因为您必须使用nodejs编写异步代码..中间件接受请求,响应和回调,并在完成后将其提供给下一个中间件......

读取上传函数返回的内容,返回一个函数,这是一个中间件..

app.route('/upload').post(middleware1, middleware2, ..., callback)

因此,如果您想直接处理回调中的上传,则必须调用它,然后将另一个函数传递给它。

app.route('/upload').post(function (request, response, next) {
    rulesUpload.upload(obj)(request, response, function(err) {
         if (!err) {
           return response.status(200).end('File Caricato/i Con Successo');
         } else {
           // do something with the err..
         }
    });
});

所以这些代码变得更复杂..所以使用中间件)