javascript 在 node.js 中计算 Content-length 标头的正确方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17922748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the correct method for calculating the Content-length header in node.js
提问by thomas-peter
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?
我完全不确定我当前计算内容长度的方法是否正确。使用 string.length() 计算内容长度的含义是什么。使用 node.js 时,将字符集设置为 utf-8 是否意味着什么?
payload = JSON.stringify( payload );
response.header( 'content-type', application/json; charset=utf-8 );
response.header( 'content-length', payload.length );
response.end( payload );
回答by Raivo Laanemets
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.
Content-Length 标头必须是响应正文中的八位字节数。payload.length
指以字符为单位的字符串长度。某些 UTF-8 字符包含多个字节。更好的方法是Buffer.byteLength(string, [encoding])
从http://nodejs.org/api/buffer.html使用。这是一个类方法,因此您不必创建任何 Buffer 实例。