twilio-labs / serverless-toolkit

CLI tool to develop, debug and deploy Twilio Functions

Home Page:https://www.twilio.com/docs/labs/serverless-toolkit

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug in handling binary files with Twilio serverless toolkit

danh182 opened this issue · 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.

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

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