Christopher
Christopher

Reputation: 1358

Serving binary/buffer/base64 data from Nodejs

I'm having trouble serving binary data from node. I worked on a node module called node-speak which does TTS (text to Speech) and return a base64 encoded audio file.

So far I'm doing this to convert from base64 to Buffer/binary and then serve it:

// var src = Base64 data
var binAudio = new Buffer(src.replace("data:audio/x-wav;",""), 'base64');

Now I'm trying to serve this audio from node with the headers like so:

res.writeHead(200, {
  'Content-Type': 'audio/x-wav',
  'Content-Length': binAudio.length
});

And serving it like so:

res.end(binAudio, "binary");

But its not working at all. Is there something I havnt quite understood or am I doing something wrong, because this is not serving a valid audio/x-wav file.

Note: The Base64 data is valid i can serve it like so [see below] and it works fine:

// assume proper headers sent and "src" = base64 data
res.end("<!DOCTYPE html><html><body><audio src=\"" + src + "\"/></body></html>");

So why can I not serve the binary file, what am I doing wrong?

Upvotes: 3

Views: 4394

Answers (1)

thejh
thejh

Reputation: 45568

Two things are wrong.

  1. not Conetnt-Length, it's Content-Length
  2. res.end(binAudio, "binary"); is wrong. Use res.end(binAudio);. With "binary", it expects a string - binary is a deprecated string encoding in node, use no encoding if you already have a buffer.

Upvotes: 3

Related Questions