Download a binary file on Node.js

I use Flash to record and upload sound to a node server. The Flash client is a variant of jrecorder . When the user records, the audio is loaded using the POST request (and not the form, because Flash cannot create files) with ByteArray audio as the POST request data (see more here ).

I can correctly get the file to Node -land using the code below, but the sound that comes out is distorted and you can’t hear anything. With that said, the contents of the file can be played by VLC and other players + Sox can encode it as mp3.

Here is my code when using Node:

var express = require('express'); var app = express(); app.use (function(req, res, next) { req.rawBody = ''; req.setEncoding('utf8'); if(req.method.toLowerCase() == "post") { req.on('data', function(chunk) { req.rawBody += chunk }); req.on('end', function() { done(req, res); }); } next(); }); function done(req, res) { fs.writeFile('abc.wav', req.rawBody, 'binary', function(err){ if (err) throw err; // Save file to S3 } } 

Now, if I use the same Flash client and make a POST request to the Rails server and use the following code, the file is saved perfectly.

 def record file = request.raw_post # Save file to S3 end 

Please note that I am not a node expert, so if you have any suggestions on what I should use instead of saving the pieces, send code examples. My main goal right now is to bring this to a working state before exploring another way to more efficiently execute node (buffers, threads, etc.).

+6
source share
1 answer

Take out the following line

 req.setEncoding('utf8'); 

You are not getting utf8 data, you are getting binary data.

You better use a buffer instead of a string

 app.use(function(req, res, next) { var data = new Buffer(''); req.on('data', function(chunk) { data = Buffer.concat([data, chunk]); }); req.on('end', function() { req.rawBody = data; next(); }); }); 
+16
source

Source: https://habr.com/ru/post/945208/


All Articles