当我想从文件中打印西里尔符号时如何修复替换字符 (�)?

How to fix replacement character (�) when I want to print cyrillic symbols from file?

当我从文件中读取行时,我试图打印一些包含英语和俄语单词的字符串。我的控制台中出现替换字符 (������) 而不是西里尔符号。如果我尝试 return 一组行,我会遇到同样的麻烦。

一条简单的线看起来像:

URL: GET /products/1234
Message: [transaction ID: 324] Отправка Get запроса: http://...//

URL: POST /products/1234
Message: [transaction ID: 324] Отправка Post запроса: http://...//

控制台打印:

URL: GET /products/1234
Message: [transaction ID: 324] ���������������: http://...//

URL: POST /products/1234
Message: [transaction ID: 324] ���������������: http://...//

同样的内容被写入数组(�而不是带有西里尔字符的行):

[
    "URL:       GET       /products/1234      Message: [transaction ID: 324 ���������������: http://...//",
    "URL:       POST       /products/1234      Message: [transaction ID: 324 ���������������: http://...//",   
]

我该如何解决?

//function to watch for file's changes:
function readFileChanges(file) {
        const Tail = require('tail').Tail;
        const tail = new Tail(file);
        let dataLines = [];
        tail.watch();
        tail.on("line", data => {
            console.log(data);
            dataLines.push(data);
        });
        return dataLines;
    };

我希望得到包含西里尔字符而不是 �-s 的行的数组:

[
    "> URL:       GET       /products/1234      Message: [transaction ID: 324] Отправка Get запроса: http://...//",

    "> URL:       POST       /products/1234      Message: [transaction ID: 324] Отправка Post запроса: http://...//"
]

和适当的控制台输出。

平台为win7和win10,节点版本为10.x

在此先感谢您!

试试这个:

const iconv = require('iconv-lite');
const Tail = require('tail').Tail;

function readFileChanges(file) {
        const tail = new Tail(file, {encoding: "binary"});
        let dataLines = [];
        tail.watch();
        tail.on("line", data => {
            data = iconv.decode(data, "cp1251").toString();
            console.log(data );
            dataLines.push(data);
        });
        return dataLines;
    };