0
module.exports.upload = function (req, res) {
  fileName = path.basename(req.query.fileName);
  var fileExtn = path.extname(req.query.fileName);
  console.log("fileName " + fileName);
  console.log("fileExtn " + fileExtn);

  var fileCheckResponse = FileCheck(req, res);  // FileCheck method containing Busboy code
  console.log("file check response =" + fileCheckResponse);
}

function FileCheck(req, res) {
var dataSize;
  var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      file.on("data", function (data) {
        dataSize=data.length;
      console.log("File [" + fieldname + "] got " + data.length + " bytes");
      console.log("the upload file data ===== " + data);

      })
    });
    busboy.on('finish', function() {
      console.log('Upload complete');
      return dataSize;
    });
   return  req.pipe(busboy);
}`

在这里从上传方法我调用存在 Busboy 代码的 FileCheck 函数,我首先调试并检查 FileCheck 函数,它命中行( busboy.on('file', function(fieldname, file, filename, encoding, mimetype) )然后它不会进入它到达另一行( busboy.on('finish', function()) 然后响应对象返回到上传方法,我期待 fileCheckResponse 中的数据长度但获取不包含它的对象,再次打开再次继续调试,它返回到 FileCheck 函数,这次它命中(file.on(“数据”,函数(数据))并在控制台上打印数据,就像我写的那样,但响应没有返回到上传方法。

再次在这里,我的问题和目标是获取数据长度作为响应,但现在我第一次将对象作为响应,而第二次指针没有返回到上传方法。

4

1 回答 1

1
// try using const or let instead of var

module.exports.upload = function (req, res) {

  fileName = path.basename(req.query.fileName);
  const fileExtn = path.extname(req.query.fileName)
  console.log("fileName " + fileName);
  console.log("fileExtn " + fileExtn);


  // try to make FileCheck function synchronous using promise or async await

  FileCheck(req, res)
    .then(fileSize => {
        console.log(fileSize, 'fileSize')
        // send whatever response you need
    })
}

function FileCheck(req, res) {
    return new Promise((resolve, reject) => {
        let dataSize;
        let busboy = new Busboy({ headers: req.headers });
        busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
            file.on('data', function (data) {
                dataSize = data.length;
                console.log("File [" + fieldname + "] got " + data.length + " bytes");
            })
        });
        busboy.on('finish', function() {
            console.log('Upload complete');
            resolve(dataSize)
        });
        req.pipe(busboy)
    })
}
于 2020-05-15T01:52:08.240 回答