【问题标题】:How to fetch and fs.writeFile a webpage with SJIS/Shift_JIS encoding如何使用 SJIS/Shift_JIS 编码获取和 fs.writeFile 网页
【发布时间】:2019-04-09 18:09:32
【问题描述】:

我正在尝试从 Internet 获取页面,然后将其保存到 HTML 文件中。该页面的标题中包含以下内容:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" >
<head>
<meta http-equiv="Content-Type" content="text/html;charset=Shift_JIS" />
</head>

不管我怎么尝试,保存的 HTML 页面看起来很糟糕,我就是无法正确保存日文字符。

我正在使用 node-fetch、fs.writeFile 和一个名为 jconv 的模块。我已经尝试了所有组合,但没有任何效果。现在,代码应该从 SJIS 转换为 UTF-8,然后fs 应该使用 UTF-8 编码写入文件。

fetch(link).
then((res) => {
    if (res.ok) {
        return res.text();
    }
    console.log("Invalid data");
}).
then((body) => {
    // this is supposed to convert from SJIS to UTF-8
    var buf = jconv.convert(body, 'SJIS', 'UTF-8');

    // save file
    fs.writeFile(path, buf, 'UTF-8', (err) => {
        if (!err) {
            console.log('Saved');
        }
    });
});

我尝试了其他编码,但最终的 HTML 文档仍然没有显示正确的特殊字符,就像在从中获取的在线页面上一样。我现在正在测试的页面是this

【问题讨论】:

    标签: encoding fs cjk node-fetch


    【解决方案1】:

    行:

    <meta http-equiv="Content-Type" content="text/html;charset=Shift_JIS" />
    

    还必须修改为:

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    

    使标头中的字符集信息与新编码匹配。

    【讨论】:

    • 我无权访问该页面的源代码。在我下载页面之后,在编码和保存之前,我必须在节点脚本中更改它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2012-12-01
    相关资源
    最近更新 更多