39

I'm not at all sure whether my current method of calculating the content-length is correct. What are the implications of using string.length() to calculate the content-length. Does setting the charset to utf-8 even mean anything when using node.js?

payload = JSON.stringify( payload );

response.header( 'content-type', application/json; charset=utf-8 );
response.header( 'content-length', payload.length );

response.end( payload );
thomas-peter
  • 7,738
  • 6
  • 43
  • 58

1 Answers1

67

Content-Length header must be the count of octets in the response body. payload.length refers to string length in characters. Some UTF-8 characters contain multiple bytes. The better way would be to use Buffer.byteLength(string, [encoding]) from http://nodejs.org/api/buffer.html. It's a class method so you do not have to create any Buffer instance.

Raivo Laanemets
  • 1,119
  • 10
  • 7
  • This fixed an issue for me where the content-length calculated through responseBody.length has a difference of 1 compared to the content-length header as given in the response. – KrekkieD Mar 04 '15 at 10:15