Question

I need to implement a HTTP server in node.js without using http module. How fun! I'm having trouble with sending the response socket.

I'm trying to fetch a file and so my code looks as follows:

fileStream = fs.createReadStream('example.jpg');
fileStream.on("end", function (close) {    
    var str = "HTTP/1.1 200 OK\r\Content-Type: image/jpeg\r\n" //and some more headers.
    socket.write(str);
    socket.pipe(fileStream);
    socket.end("\r\n");
});

What am I missing?

I am of course using net module to get the socket and fs as well.

Was it helpful?

Solution

There are two main issues with the code you have.

  • Responses as formatted as headers followed by two sets of "\r\n", and then the content. The "\r\n" in your end() call should be in str. You also are missing an 'n' from the first "\r\n".
  • You are trying to pipe the contents of the readstream, which is great, but you are doing all of this inside of the steam's end(), so the pipe as nothing left to send because the data was all already emitted.

Try something like this instead. Create the read stream, send the response and pipe then rest.

var str = "HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\n\r\n";
socket.write(str);
var fileStream = fs.createReadStream('example.jpg');
fileStream.pipe(socket);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top