【问题标题】:Buffer not recognized as buffer on nodejs with sails js使用sails js的nodejs上的缓冲区不被识别为缓冲区
【发布时间】:2019-03-10 09:51:12
【问题描述】:

我正在尝试从发送到 SailsJs 服务器的 blob 中获取缓冲区。

发送到服务器的示例如下:

Blob(3355) {size: 3355, type: "video/x-matroska;codecs=avc1,opus"}

在服务器端,我执行以下操作:

let body = new Array(0);
let buffer;
let readable = req.file('recordingPart');

readable.on('data', (chunk) => {
  body.push(new Buffer(chunk));
});

readable.on('end', () => {
  buffer = Buffer.concat(body);
  console.log('There will be no more data.', buffer.length, buffer);
});

运行这部分代码时出现错误:

 buffer.js:226
  throw new errors.TypeError(
  ^

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, buffer, arrayBuffer, array, or array-like object. Received type object
    at Function.from (buffer.js:226:9)
    at new Buffer (buffer.js:174:17)
...

在这种情况下,错误位于new Buffer(chunk) 上的body.push(new Buffer(chunk));

我的第一个方法是类似的:

    let body = [];
    let buffer;
    let readable = req.file('recordingPart');

    readable.on('data', (chunk) => {
      body.push(chunk);
    });

    readable.on('end', () => {
      buffer = Buffer.concat(body);
      console.log('There will be no more data.', buffer.length, buffer);
    });

但我遇到了这个错误:

    buffer.js:475
      throw kConcatErr;
      ^

TypeError [ERR_INVALID_ARG_TYPE]: The "list" argument must be one of type array, buffer, or uint8Array
    at buffer.js:450:20

在这个错误中弹出Buffer.concat(body);

我从这个答案Node.js: How to read a stream into a buffer?得到了一些指导

谁能帮我从req.file获取buffer

【问题讨论】:

    标签: javascript node.js stream sails.js buffer


    【解决方案1】:

    您当前的上传方式可行,但您可能需要考虑另一种新方式:

    // Upload the image.
    var info = await sails.uploadOne(photo, {
      maxBytes: 3000000
    })
    // Note: E_EXCEEDS_UPLOAD_LIMIT is the error code for exceeding
    // `maxBytes` for both skipper-disk and skipper-s3.
    .intercept('E_EXCEEDS_UPLOAD_LIMIT', 'tooBig')
    .intercept((err)=>new Error('The photo upload failed: '+util.inspect(err)));
    

    Full Example Here

    还可以查看Sails.JS Platzi Course,了解有关使用示例项目 Ration 的最新上传功能的视频教程。

    【讨论】:

      【解决方案2】:

      您可以获得uploadedFile,如下所示。

      req.file('recordingPart').upload(function (err, uploadedFiles){
      
        if (err) return res.serverError(err);
      
        // Logic with uploadedFiles goes here
      
      });
      

      您可以从uploadedFiles[0].fd 获取文件描述符并使用它来读取/流式传输文件,如下所示。

      fs.readFile(uploadedFiles[0].fd, 'utf8', function (err,data) {
      
         // Logic with data goes here 
         var myBuffer = Buffer.from(data);
      });
      

      如上使用fs 创建fs 实例如下。

      var fs = require('fs');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-12
        • 2023-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        相关资源
        最近更新 更多