4

I'm trying to get the buffer from a blob being sent to my SailsJs server.

An example of what is being sent to the server is this:

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

Once on the server side, I do the following:

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

When running this part of the code I get the error:

 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)
...

In this case the error is at the body.push(new Buffer(chunk)); on new Buffer(chunk)

My first approach was similar:

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

but I've got this error:

    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

In this one the error pops at Buffer.concat(body);

I got some guidance from this answer Node.js: How to read a stream into a buffer?

Can anyone help me in getting the buffer from that req.file.

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
jonystorm
  • 548
  • 4
  • 17

2 Answers2

0

Your current upload approach will work but there's another new way you might want to consider:

// 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

Also check out the Sails.JS Platzi Course for video tutorials on this latest upload functionality using the example project Ration.

johnabrams7
  • 399
  • 2
  • 10
0

You can get uploadedFile as below.

req.file('recordingPart').upload(function (err, uploadedFiles){

  if (err) return res.serverError(err);

  // Logic with uploadedFiles goes here

});

You can get file descriptor from uploadedFiles[0].fd and use it to read/stream the file as below.

fs.readFile(uploadedFiles[0].fd, 'utf8', function (err,data) {

   // Logic with data goes here 
   var myBuffer = Buffer.from(data);
});

To use fs as above create fs instance as below.

var fs = require('fs');
Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45