2

I need to implement a web server using only net module and socket.write commands. I'm using the following code for sending text files (html, css and etc):

fs.readFile(file,encoding='UTF8', function (err, data) {
if (err) throw err;
var dataToReturn=data.toString();
socket.write('Content-Length:'+dataToReturn.length+'\r\n');
socket.write('\r\n');
socket.write(dataToReturn);
});

Its working fine, but it doesn't work when I need to send image files. What should I do?

2 Answers 2

3

By setting the encoding to utf8, you have explicitly told Node to convert your file into a text string, but it is a binary image so the conversion process will probably corrupt some of the data and make you have the incorrect length. Leave the data as a Buffer like this:

fs.readFile(file, function (err, data) {
    if (err) throw err;
    socket.write('Content-Length: ' + data.length + '\r\n');
    socket.write('\r\n');
    socket.write(data);
});
Sign up to request clarification or add additional context in comments.

Comments

1
fs.readFile(file, function (err, data) {
  if (err) throw err;
  //Content-Length should be binary length not string length
  socket.write('Content-Length:'+data.length+'\r\n');

  socket.write('\r\n');
  socket.write(data);
});

You may need a content-type to make your response more valid :)

socket.write('Content-Type:' + mimetype + '\r\n');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.