这里是文章模块栏目内容页
busbody在nodejs中的运用

busbody是一个中间件,判断post等其他非get和head请求的body内容中某个变量是否满足预设值;

需要 ContentType标头指定为“application/x-www-formurlencode”或以“MultiPart/*”开头。

引入

npm install connect-busboy

在nodejs中使用:

 var busboy = require('connect-busboy');
 
 app.use(busboy({
  limits: {
    fileSize: bytes( 1024 *1024 )
  }
}));

#app是 express 的实例,

监听触发fileSize变量是否超过设置值:

exports.upload = function (req, res, next) {
  var isFileLimit = false;
  req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
      file.on('limit', function () {
        isFileLimit = true;

        res.json({
          success: false,
          msg: 'File size too large. Max is ' + config.file_limit
        })
      });

      #如果没触发limits 的 fileSize大小,继续这里执行下去
     req.pipe(req.busboy);
};

 

这个 pipe 是 Stream 里面的方法,文档在这里:

https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options

简单的说就是把一个 readable stream 的所有数据写入到另一个 writable stream 里面去。