Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct method for calculating the Content-length header in node.js

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 ); 
like image 456
thomas-peter Avatar asked Jul 29 '13 11:07

thomas-peter


People also ask

How is content length calculated?

As bytes are represented with two hexadecimal digits, one can divide the number of digits by two to obtain the content length (There are 12 hexadecimal digits in "48656c6c6f21" which equates to six bytes, as indicated in the header "Content-Length: 6" sent from the server).

What is content type header in node JS?

Content-Type in the response is the header we can set to inform how client would interpret the data from the server. For example, if you are sending down an HTML file to the client, you should set the Content-Type to text/html, which you can with the following code: response. setHeader("Content-Type", "text/html");

How does JSON calculate content length?

you should use JSON. stringify() to get the complete string then apply length attribute to get length. var data = { "Id": 1, "Value": 10, "UId" : "ab400" } var Length = JSON. stringify(data).

Is length a method in Javascript?

The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings. Although the syntax of the length function remains the same, bear in mind that the interpretation of length varies between arrays and strings.


1 Answers

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.

like image 169
Raivo Laanemets Avatar answered Oct 10 '22 11:10

Raivo Laanemets