Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 285
Christopher Avatar asked May 09 '26 14:05

Christopher


1 Answers

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.
like image 87
thejh Avatar answered May 11 '26 06:05

thejh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!