是否可以使用nodejs加载ansi编码的字符串

Is it possible to load ansi encoded string using nodejs

我有大量 html 个文件(大约 2k)。
这些 html 是从 word 文档转换的结果。
这些文件在 html 标签内有一些希伯来文文本。我可以使用 vscode 或 notepad++ 编辑器完美地看到文本。

我的目标是遍历文件夹并将文件内容插入到某个数据库中。 由于我对 nodejs 知之甚少 - 我决定使用 node.js 构建 "looping"。 这是我到目前为止完成的地方:

fs.readdir('./myFolder', function (err, files) {
    total = files.length;

    let fileArr = []
    for(var x=0, l = files.length; x<l; x++) {
      const content = fs.readFileSync(`./myFolder/${files[x]}`, 'utf8');    

      let title = content.match(/<title>(.*?)<\/title>/g).pop()

      fileArr.push({id:files[x] , title})
    }
});

问题是:虽然文本在编辑器中正确显示 - 调试时 - 我可以看到 "title" 变量获取由问号组成的字符串

我想问题出在文件编码上,我在这里吗?
如果是这样 - 有没有办法解码字符串?

P.S。我的 OS 是 windows10

谢谢

这里有几种可能性,您的输入文件可能采用多字节编码(例如 utf8 utf16 等),并且您的调试器由于字体限制而无法显示正确的字符。

我会尝试将标题变量写入某个测试文件,如下所示:

fs.writeFileSync(`title-test-${x}.txt`, title, "utf8");

然后查看标题在您的文本编辑器中是否正确。

文件也可能以 extended ascii encoding such as Windows 1255 or ISO 8859-8. If this is the case, fs.readFileSync will not work correctly since it does not support these encodings (see node.js encoding list)

编码

如果文件使用 single-byte 扩展的 ascii 编码进行编码,应该可以转换为更便携的编码(例如 utf8)。

为此,我推荐 iconv-lite 模块,您可以用它做很多事情!

例如,要将 Windows 1255 文件转换为 utf8,您可以尝试:

    const iconv = require("iconv-lite");
    const fs = require("fs");

    // Convert from an encoded buffer to JavaScript string.
    const fileData = iconv.decode(fs.readFileSync("./hebrew-win1255.txt"),  "win1255");

    // Convert from JavaScript string to a buffer.
    const outputBuffer = iconv.encode(fileData, "utf8");

    // Write output file..
    fs.writeFileSync("./hebrew-utf8-output.txt", outputBuffer);