2016-02-03 53 views
0

我有一個劇本的NodeJS讀取文件上的「o」,而且比在控制檯上打印一個段落。腳本的NodeJS不打印的字符,如Windows終端

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 

重音字符不打印在終端上。順便說一下,可以在終端重音字符上打印,我的腳本的最後一行證明了它。

+0

你能否提供你的文本文件,因爲它完全適合我。 –

+0

該文件如下:https://www.google.it/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjG_7O33t3KAhVF1ywKHWCNCVAQFggfMAA&url=http%3A%2F%2Fwww.hoepliscuola.it %2Fdownload%2F2842%2Fla-神曲 - 即興-txt.aspx與USG = AFQjCNG9GLc-QsAyIzTKX0UluZjlrGEw1Q&SIG2 = DTzeFHszNSHSULrvT0RdCQ與BVM = bv.113370389,d.bGg – optimusfrenk

+0

檢查我的答案;) –

回答

1

問題是你的file不在utf8,是windows-1252編碼文件。

enter image description here

使用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並使用您的代碼。