node js return received data in-rest api response

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



node js return received data in-rest api response



i create simple rest api to return media file


var fs = require('fs')
var express = require('express')
var app = express()
app.get('/file.ogg', function (req, res)
res.set(
'Content-Type': 'audio/ogg',
'Transfer-Encoding': 'chunked'
);

var inputStream = fs.createReadStream(__dirname + '/1.ogg');
inputStream.pipe(res);
);

var server = app.listen(3002);



if i call http://127.0.0.1:3002/file.ogg



server read file 1.ogg and return it in response.



now i use websocket to get file data from external device


socket.on('message', function incoming(message)

var data = JSON.parse(message);
console.log('fileName: ' + data.fileName);
console.log('fileData : ' + data.fileData.length);

var path =__dirname + '/_' + data.fileName;
var buf = Buffer.from(data.fileData, 'base64');

console.log('buf : ' + buf.length);

// save data to file
fs.appendFile(path ,buf ,function(err)
if(err) throw err;
);

);



i want to return data (buf) in response like first example but without saving any think, how i can do this.




1 Answer
1



If your files are large, you may want to pull in an additional websocket streaming library which will allow you to stream the data back to the client. socket.io-stream was created specifically to allow that. From their examples:


// send data
ss(socket).on('file', function(stream)
fs.createReadStream('/path/to/file').pipe(stream);
);

// receive data
ss(socket).emit('file', stream);
stream.pipe(fs.createWriteStream('file.txt'));





there is 2 devices A & B, A send message to B with WS (websocket) ,if i use this command i will send received message to A.
– joseph
Aug 12 at 11:08





Updated answer, but I'm still not entirely sure about what you're trying to do. Once you get the message from device A, where do you want to send a response back to? Where's the client in that scenario? Is the file data going back to the requesting socket (device A), or a different server/client?
– willascend
Aug 12 at 15:13





client is browser like first example, in the first example i read from file, but now i want to read from websocket
– joseph
Aug 13 at 11:03






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered