简体   繁体   中英

How to send a http response without using http module in node.js?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM