How to convert data in utf-8 to node.js?

I am using node.js with an expression. I read data from MongoDB using Mongoose and delivered it in the usual way using res.send(data) . Unfortunately, some requests are not delivered. Despite this, the header says the encoding is utf-8, in some cases it seems to be ANSI, as a result of which the jsonp callback function fails with an error.

You can reproduce the error on this page: http://like-my-style.com/#!single/9837034 . The jsonp call is not suitable for some products, most of them (as well as special characters) work fine.

How can I guarantee that a given String is encoded in utf-8 in node.js?

+6
source share
3 answers

You tried:

 res.send(data.toString("utf8")); 

So that your data is in utf8 and not Buffer.

+7
source

I think I am stuck in a similar problem and the neebz solution worked, but I had to put it in the right place.

 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 document node.js, it is documented as request.setEncoding (), which may be an error because it must be called on the res object created by the request.

+1
source

You specify the type of encoding

res.setEncoding('utf8');

?

0
source

Source: https://habr.com/ru/post/886188/


All Articles