nodeJS:将 response.body 转换为 utf-8(来自 windows-1251 编码)

nodeJS: convert response.body in utf-8 (from windows-1251 encoding)

我正在尝试将 windows-1251 中编码的 HTML 正文转换为 utf-8,但我仍然在 html.

上弄乱了字符

它们基本上是俄语字母表,但我无法正确显示它们。我得到 ??????? ?? ???

const GOT = require('got') // https://www.npmjs.com/package/got
const WIN1251 = require('windows-1251') // https://www.npmjs.com/package/windows-1251

async function query() {
    var body = Buffer.from(await GOT('https://example.net/', {resolveBodyOnly: true}), 'binary')
    var html = WIN1251.decode(body.toString('utf8'))
    console.log(html)
}

query()

你在这里来回做了很多愚蠢的编码。而且“背”甚至与“前”都不匹配。

首先,您使用got库下载一个网页;默认情况下,got will dutifully decode response texts as UTF-8. You stuff the returned Unicode string into a Buffer with the binary encoding, which throws away the higher octet of each UTF-16 code unit of the Unicode string. Then you use .toString('utf-8') 将这个残缺的字符串解释为 UTF-8(实际上,它很可能根本不是有效的 UTF-8)。然后将“UTF-8”字符串传递给 windows-1251,将其解码为“代码页 1251”字符串。所有这些混乱不可能带来任何好处。

您要使用的 windows-1251 包将所谓的“二进制”(伪拉丁-1)字符串作为输入。您应该做的是获取二进制响应,将其解释为 Latin-1/‘binary’ string,然后将其传递给 windows-1251 库进行解码。

换句话说,使用这个:

const GOT = require('got');
const WIN1251 = require('windows-1251');

async function query() {
    const body = await GOT('https://example.net/', {
        resolveBodyOnly: true,
        responseType: 'buffer'
    });
    const html = WIN1251.decode(body.toString('binary'))
    console.log(html)
}

query()