nodejs讀取本地中文json文件出現(xiàn)亂碼解決方法
1. 確定json文件是UTF-8 無BOM編碼的的。如果有BOM,會在讀取第一行的時候出現(xiàn)亂碼。
Per "fs.readFileSync(filename, 'utf8') doesn't strip BOM markers #1918", fs.readFile is
working as designed: BOM is not stripped from the header of the UTF-8 file, if it exists. It at the discretion of the developer to handle this.
Possible workarounds:
- data= data.replace(/^\uFEFF/, ''); perhttps://github.com/joyent/node/issues/1918#issuecomment-2480359
- Transform the incoming stream to remove the BOM header with the NPM module bomstrip perhttps://github.com/joyent/node/issues/1918#issuecomment-38491548
What you are getting is the byte order mark header (BOM) of the UTF-8 file. When JSON.parse sees
this, it gives an syntax error (read: "unexpected character" error). You must strip the byte order mark from the file before passing it to JSON.parse:
fs.readFile('./myconfig.json', 'utf8', function (err, data) {
myconfig = JSON.parse(data.toString('utf8').replace(/^\uFEFF/, ''));
});
// note: data is an instance of Buffer
2. 確定json沒有格式錯誤。我在用utf8編碼并用utf8 encoding來讀取文件之后依然報錯,百思不得其解。
最后發(fā)現(xiàn)json有兩個editor沒有發(fā)現(xiàn)的格式錯誤,一個是一個數(shù)組中兩個元素之間少了一個“,”,另一個是另一個數(shù)組最后多了一個“,”。
注1:Node的iconv模塊,僅支持linux,不支持Windows,因此要用純js的iconv-lite,另:作者說iconv-lite的性能更好,具體參考Git站點:iconv-lite
注2:我在測試讀寫文件時,始終無法把中文寫入文件,一直亂碼,讀取正常,后來同事幫我發(fā)現(xiàn):js文件的編碼格式是ansi,nodejs的代碼文件必須是utf8格式
注3:如果程序操作的文件,都是以UTF8編碼格式保存的,那么就不需要使用iconv模塊,直接以utf8格式讀取文件即可,如:
// 參數(shù)file,必須保存為utf8格式,否則里面的中文會亂碼
function readFile(file){
// readFile的第2個參數(shù)表示讀取編碼格式,如果未傳遞這個參數(shù),表示返回Buffer字節(jié)數(shù)組
fs.readFile(file, "utf8", function(err, data){
if(err)
console.log("讀取文件fail " + err);
else{
// 讀取成功時
console.log(data);// 直接輸出中文字符串了
}
});
}
nodejs讀取中文文件編碼問題
準備一個文本文件(當然也可以是csv文件等)test.txt和text.csv,nodejs文件test.js如下:
var iconv = require('iconv-lite');
var fs = require('fs');
var fileStr = fs.readFileSync('D:\\test.csv', {encoding:'binary'});
var buf = new Buffer(fileStr, 'binary');
var str = iconv.decode(buf, 'GBK');
console.log(str);
直接讀文件的話是亂碼,不信你可以試試。需要先統(tǒng)一用二進制編碼方式讀取,然后再用GBK解碼。
相關(guān)文章
Javascript使用post方法提交數(shù)據(jù)實例
這篇文章主要介紹了Javascript使用post方法提交數(shù)據(jù),實例分析了javascript實現(xiàn)post提交數(shù)據(jù)的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08
IE9+已經(jīng)不對document.createElement向下兼容的解決方法
這篇文章主要介紹了IE9+已經(jīng)不對document.createElement向下兼容的解決方法,需要的朋友可以參考下2015-09-09
uniapp開發(fā)安卓App實現(xiàn)高德地圖路線規(guī)劃導航功能的全過程
最近項目需要在APP內(nèi)實現(xiàn)路線規(guī)劃導航功能,直接打開高德地圖進行導航,下面這篇文章主要給大家介紹了關(guān)于利用uniapp開發(fā)安卓App實現(xiàn)高德地圖路線規(guī)劃導航功能的相關(guān)資料,需要的朋友可以參考下2022-08-08
JavaScript偽數(shù)組和數(shù)組的使用與區(qū)別
這篇文章主要給大家介紹了關(guān)于JavaScript偽數(shù)組和數(shù)組使用與區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05

