Node.js sending HTTP binary data over a socket

I am writing my own http module (I know that node.js includes one) I use a network module when I receive a request for a static binary file (file), how do I generate an HTTP response with a binary file? When I do just that for a text file (e.g. html file), it just works.

+4
source share
1 answer

If you are using a network module, you are probably using code, for example:

var server = net.createServer(function (socket) { }); 

What is a socket? it represents the data stream over the network. In objects, Socket is a WriteableStream, in more detail here: http://nodejs.org/docs/v0.6.5/api/streams.html

When you read a file, you can get the content as String, Buffer or as ReadableStream

The easiest way to read the file as a stream is to use the function: http://nodejs.org/docs/v0.6.5/api/fs.html#fs.createReadStream for example

 var fileAsAstream = fs.createReadStream(filePath); 

To transfer the contents of a binary read stream to a write stream, you can use the function " http://nodejs.org/docs/v0.6.5/api/streams.html#stream.pipe for example.

 fileAsAstream.pipe(socket); 
+3
source

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


All Articles