serverless-toolkit icon indicating copy to clipboard operation
serverless-toolkit copied to clipboard

Bug in handling binary files with Twilio serverless toolkit

Open danh182 opened this issue 2 years ago • 1 comments

The Twilio serverless toolkit is not able to correctly serve an mp3 file in a response. I'm following a guide in the docs here and I've got it working completely fine using the web services editor in the console. However when I try to replicate the code locally with serverless, it doesn't work.

The JS file at functions/handler.js is public and I have an mp3 file at assets/hello.mp3 which is private. The JS is:

const fs = require('fs');

exports.handler = function(context, event, callback) {
  var phrase = event.phrase;
  
  var filePath = Runtime.getAssets()[`/${phrase}.mp3`].path;
  var buffer = fs.readFileSync(filePath);
  var stat = fs.statSync(filePath);
  
  var response = new Twilio.Response();
  
  response.setBody(buffer);
  response.appendHeader('Content-Type', 'audio/mpeg');
  response.appendHeader('Content-Length', stat.size);
  
  return callback(null, response);
};

The only change from the docs is that phrase is a get parameter and allows the user to specify the filename. When I request http://localhost:3000/handler?phrase=hello Chrome detects that it's receiving an audio file (the headers are set correctly) but doesn't play it. The response is:

{type: "Buffer",…}
    data: [255, 243, 68, 196, 0, 17, 82, 130, 20, 0, 24, 68, 185, 52, 68, 74, 44, 234, 110, 238, 250, 23, 204,…]
    type: "Buffer"

This looks like the serverless toolkit is not encoding the binary data correctly. I've replicated the issue using Node v14 and v16, on Windows and CentOS.

danh182 avatar Aug 23 '22 07:08 danh182

Thank you so much for opening your first issue in this project! We'll try to get back to it as quickly as possible. While you are waiting...here's a random picture of a corgi (powered by dog.ceo)

picture of dog

welcome[bot] avatar Aug 23 '22 07:08 welcome[bot]

Hi! Just use response.setBody(new AudioBuffer(buffer)); instead of response.setBody(buffer);. Tested on node18 and latest chrome

makserik avatar Apr 17 '24 11:04 makserik