javascript 在 Node.js 中从 Windows-1251 转换为 UTF-8
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8693400/
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
Converting from Windows-1251 to UTF-8 in Node.js
提问by user1125115
I need to convert a string from Windows-1251 to UTF-8.
我需要将字符串从 Windows-1251 转换为 UTF-8。
I tried to do this with iconv, but all I get is something like this:
我试图用iconv来做到这一点,但我得到的只是这样的:
п??п??п??п??п?? п??п??п??п??п??п?? п??п??п??п??п??п??п??п??
п??п??п??п??п?? п??п??п??п??п??п?? п??п??п??п??п??п??п??п??
var iconv = new Iconv('windows-1251', 'utf-8')
title = iconv.convert(title).toString('utf-8')
回答by sensor
Here is working solution to your problem. You have to use Buffer and convert your string to binary first.
这是您问题的有效解决方案。您必须先使用 Buffer 并将字符串转换为二进制。
const Iconv = require('iconv').Iconv;
request({
uri: website_url,
method: 'GET',
encoding: 'binary'
}, function (error, response, body) {
const body = new Buffer(body, 'binary');
conv = Iconv('windows-1251', 'utf8');
body = conv.convert(body).toString();
});