【问题标题】:Nodejs script doesn't print characters like 'ò' on the windows terminalNodejs脚本不会在Windows终端上打印像'ò'这样的字符
【发布时间】:2016-02-04 22:25:16
【问题描述】:

我有一个读取文件的 Nodejs 脚本,然后在控制台上打印一个段落。

var fs = require('fs');
var math = require('mathjs');

var piece = "";
var path = "./divina_commedia.txt";
var stats = fs.statSync(path);
var start = math.round(math.random(stats.size));
var opt = { flags: 'r', encoding: 'utf8', autoclose: true, start: start, end: start + 2000 };
var input = fs.createReadStream(path, opt);
input.on('end', () => { clean() })
input.on('data', store);

function store(chunk) {
    piece = piece + chunk;
}

function clean() {
    var subs = piece.match(/[A-Z][^\.]*\./g);
    console.log(subs[0] + subs[1]);
}

console.log("ò"); // <<-- this is printed on the terminal

重音字符不会打印在终端上。顺便说一句,可以在终端重音字符上打印,我的脚本的最后一行证明了这一点。

【问题讨论】:

  • 您能否提供您的文本文件,因为它非常适合我。
  • 文件如下:google.it/…
  • 感谢您的帮助,但我找到了将编码设置为“二进制”的解决方案

标签: node.js windows character-encoding


【解决方案1】:

问题是您的file 不在utf8 中,是windows-1252 编码文件。

使用iconv-lite对其进行解码。

var fs = require('fs');
var math = require('mathjs');
var iconv = require('iconv-lite');

var piece = "";
var path = "./divina_commedia.txt";

var opt = {
    flags: 'r',
    autoclose: true,
    start: start,
    end: start + 2000
    //remove utf8
};

var input = fs.createReadStream(path, opt)
              .pipe(iconv.decodeStream('win1252')); //decode

input.on('end', clean);
input.on('data', store);

function store(chunk) {
    piece = piece + chunk;
}

function clean() {
    piece = piece.toString(); //Buffer to string
    var subs = piece.match(/[A-Z][^\.]*\./g);
    console.log(piece); //ò printed correctly
}

或者您可以事先将文件转换为 utf8 并使用您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2021-12-26
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多