溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用nodejs讀取本地json文件出現(xiàn)亂碼如何解決

發(fā)布時(shí)間:2021-06-15 16:34:52 來(lái)源:億速云 閱讀:352 作者:Leah 欄目:web開(kāi)發(fā)

今天就跟大家聊聊有關(guān)使用nodejs讀取本地json文件出現(xiàn)亂碼如何解決,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

1. 確定json文件是UTF-8 無(wú)BOM編碼的的。如果有BOM,會(huì)在讀取第一行的時(shí)候出現(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沒(méi)有格式錯(cuò)誤。我在用utf8編碼并用utf8 encoding來(lái)讀取文件之后依然報(bào)錯(cuò),百思不得其解。

最后發(fā)現(xiàn)json有兩個(gè)editor沒(méi)有發(fā)現(xiàn)的格式錯(cuò)誤,一個(gè)是一個(gè)數(shù)組中兩個(gè)元素之間少了一個(gè)“,”,另一個(gè)是另一個(gè)數(shù)組最后多了一個(gè)“,”。

注1:Node的iconv模塊,僅支持linux,不支持Windows,因此要用純js的iconv-lite,另:作者說(shuō)iconv-lite的性能更好,具體參考Git站點(diǎn):iconv-lite

注2:我在測(cè)試讀寫文件時(shí),始終無(wú)法把中文寫入文件,一直亂碼,讀取正常,后來(lái)同事幫我發(fā)現(xiàn):js文件的編碼格式是ansi,nodejs的代碼文件必須是utf8格式

注3:如果程序操作的文件,都是以UTF8編碼格式保存的,那么就不需要使用iconv模塊,直接以u(píng)tf8格式讀取文件即可,如:

// 參數(shù)file,必須保存為utf8格式,否則里面的中文會(huì)亂碼  
function readFile(file){  
    // readFile的第2個(gè)參數(shù)表示讀取編碼格式,如果未傳遞這個(gè)參數(shù),表示返回Buffer字節(jié)數(shù)組  
    fs.readFile(file, "utf8", function(err, data){  
        if(err)  
            console.log("讀取文件fail " + err);  
        else{  
            // 讀取成功時(shí)  
            console.log(data);// 直接輸出中文字符串了  
        }  
    });  
}

nodejs讀取中文文件編碼問(wèn)題

準(zhǔn)備一個(gè)文本文件(當(dāng)然也可以是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);

看完上述內(nèi)容,你們對(duì)使用nodejs讀取本地json文件出現(xiàn)亂碼如何解決有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI