0

Using the help of busboy I am attempting to save FileStream into a Firebase bucket.

code:

const admin = require('firebase-admin');
const userFilesBucket = admin.storage().bucket(USER_FILES_BUCKET_NAME);


function handlePost(req, res){
  const busboy = new Busboy({ headers: req.headers })

  busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    file.on('data', function(data) {
    });
    file.on('end', function() {
      uploadFile({filename: filename, file:file, mimetype:mimetype})
        .catch(err => {
          console.log("attemptFileUpload | err:", err)
          reject(err)
        });
    });
  });
}

function uploadFile(fileContainer){

  const filePath = fileContainer.filename

  const file = userFilesBucket.file(filePath);

  file.save(fileContainer.file, function(err) {
    if (!err) console.log('Sucess | uploaded a blob or file!');
  });
}

This will succeed and the file is saved to bucket but at the same time the above Promise catches exception:

The "chunk" argument must be one of type string or Buffer. Received type object

as well as the files are corrupt. This error tells me I should convert the FileStream to Buffer?

I should also note, that the fileContainer.file is of type FileSream.

Thanks.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
KasparTr
  • 2,328
  • 5
  • 26
  • 55

1 Answers1

0

The solution was very simple, a miss-read of busboy doc on my part.

Needed to use busboy's file.on(data) listener to access the file data as Buffer, not the original incoming file as FileStream.

busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  file.on('data', data => {
    uploadFile({filename: filename, file:data, mimetype:mimetype})
      .catch(err => {
        console.log("attemptFileUpload | err:", err)
      });
  });
  file.on('end', function() {
      // move from here, up to file.on(data)
  });
});  
KasparTr
  • 2,328
  • 5
  • 26
  • 55