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.
str
. You also are missing an 'n' from the first "\\r\\n". 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.