我试图从互联网上获取一个页面,然后将其保存到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
这条线:
<meta http-equiv="Content-Type" content="text/html;charset=Shift_JIS" />
还必须修改为:
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
使标头中的字符集信息与新编码匹配。