如何在 node.js 中将数据转换为 utf-8?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5708872/
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
How to convert data to utf-8 in node.js?
提问by Thomas
I am using node.js with express. I read out data from MongoDB with Mongoose and deliver it the normal way with res.send(data). Unfortunately the delivering fails for some requests. Even so the header says the encoding is utf-8, it seems to be ANSI in some cases, causing the jsonp callback function to fail with an error.
我正在使用带有 express 的 node.js。我使用 Mongoose 从 MongoDB 中读取数据,并使用res.send(data). 不幸的是,某些请求的传递失败。即便如此header说编码是utf-8,但在某些情况下似乎是ANSI,导致jsonp回调函数失败并报错。
You can reproduce the error at this page: http://like-my-style.com/#!single/9837034. The jsonp call fails just on some products, most of them (also the ones with special chars) work fine.
您可以在此页面重现错误:http: //like-my-style.com/#! single/9837034。jsonp 调用仅在某些产品上失败,其中大多数(还有具有特殊字符的产品)工作正常。
How can I ensure, that a given String is encoded in utf-8 in node.js?
如何确保给定的字符串在 node.js 中以 utf-8 编码?
采纳答案by Van Nguyen
Have you tried:
你有没有尝试过:
res.send(data.toString("utf8"));
To ensure that your data is in utf8 and is not Buffer.
确保您的数据在 utf8 中而不是 Buffer。
回答by bdavis
I think I got stuck in a similar issue and neebz solution worked but I had to put it in the right spot.
我想我陷入了类似的问题,neebz 解决方案奏效了,但我必须把它放在正确的位置。
var req = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
**res.setEncoding(encoding='utf8');**
res.on('data', function(d) {
console.log(d);
});
});
In the node.js docs its documented as request.setEncoding() which might be an error because it needs to be called on the res object that is created by the request.
在 node.js 文档中,它记录为 request.setEncoding() 这可能是一个错误,因为它需要在由请求创建的 res 对象上调用。
回答by neebz
Are you setting the encoding type
您是否设置编码类型
res.setEncoding('utf8');
res.setEncoding('utf8');
?
?

