2013-04-02 73 views
14

我正在嘗試讀取節點中屬性文件的內容。這是我的電話:編碼在fs.readFile中被忽略

fs.readFile("server/config.properties", {encoding: 'utf8'}, function(err, data) { 
    console.log(data); 
}); 

控制檯打印緩衝區:

<Buffer 74 69 74 69 20 3d 20 74 6f 74 6f 0a 74 61 74 61 20 3d 20 74 75 74 75> 

當我替換此代碼:

fs.readFile("server/config.properties", function(err, data) { 
    console.log(data.toString('utf8')); 
}); 

它工作正常。但node documentation說字符串轉換如果編碼的選項

傳遞給UTF8

節點 - 版本的輸出v0.10.2

缺少什麼我在這裏?

感謝您的支持

+0

兩種方式都適用於我。您可能正在使用較舊版本的節點?我正在使用v0.10.1 – Anton

回答

29

根據您正在運行的節點版本的不同,參數可能只是encoding

fs.readFile("server/config.properties", 'utf8', function(err, data) { 
    console.log(data); 
}); 

的第二個參數更改爲optionswith v0.10

  • FS readFile()writeFile()appendFile()和他們同步同行現在採取options對象(但舊的API,一個encoding串,仍然支持)

對於前者文檔:

+0

這個技巧。但我使用的是最新的節點版本: –

5

您應該將{encoding: 'utf8'}更改爲{encoding:'utf-8'},對於e xample:

fs.readFile("server/config.properties", {encoding: 'utf-8'}, function(err, data) { 
console.log(data); 
}); 
+0

無論如何,fs不支持像ISO-8859-1這樣的字符集,因爲這個原因我使用這個答案http://stackoverflow.com/a/14551669/2979435 – deFreitas