2011-11-12 63 views
0

我有一個相當簡單的腳本,它嘗試讀取並解析JSON文件。 JSON非常簡單,我很確定它是有效的。異步和同步讀取的不同結果

{ 
    "foo": "bar" 
} 

現在,我一直在試着用fs.readFile來讀取它。讀取時不會發生錯誤,並且返回的數據是字符串。唯一的問題是該字符串是空的。

我重複了我的代碼,但使用了fs.readFileSync,這完全使用相同的路徑返回文件。兩者都有指定的utf-8編碼。

這是非常簡單的代碼,你可以看到。

fs.readFile('./some/path/file.json', 'utf8', function(err, data) { 
    if(!err) { 
     console.log(data); // Empty string... 
    } 
}); 

console.log(fs.readFileSync('./some/path/file.json', 'utf8')); // Displays JSON file 

它可能是權限或所有權嗎?我已經嘗試了許可集755777無濟於事。

我正在運行節點v0.4.10。任何建議指向我在正確的方向將非常感激。謝謝。

編輯:這是我的實際代碼塊。希望這會給你一個更好的主意。

// Make sure the file is okay 
fs.stat(file, function(err, stats) { 
    if(!err && stats.isFile()) { 
     // It is okay. Now load the file 
     fs.readFile(file, 'utf-8', function(readErr, data) { 
      if(!readErr && data) { 
       // File loaded! 
       // Now attempt to parse the config 
       try { 
        parsedConfig = JSON.parse(data); 
        self.mergeConfig(parsedConfig); 

        // The config was loaded and merged 
        // We can now call the callback 
        // Pass the error as null 
        callback.call(self, null); 

        // Share the news about the new config 
        self.emit('configLoaded', file, parsedConfig, data); 
       } 
       catch(e) { 
        callback.call(self, new Error(file + ': The config file is not valid JSON.')); 
       } 
      } 
      else { 
       callback.call(self, new Error(file + ': The config file could not be read.')); 
      } 
     }); 
    } 
    else { 
     callback.call(self, new Error(file + ': The config file does not exist.')); 
    } 
}); 
+1

我在代碼中看不到utf8。這是實際的代碼? – thejh

+0

對不起,不是,我剛剛輸入了一個副本,我會添加UTF-8。 – Olical

+0

@thejs我添加了一段我的實際代碼。我可以向你保證'file'變量是一個字符串並且轉到正確的文件。 – Olical

回答

1

這很奇怪。

代碼看起來。

var fs = require('fs'); 

fs.readFile('./jsonfile', 'utf8', function(err, data) { 
     if(err) { 
       console.error(err); 
     } else { 
       console.log(data); 
       parsedConfig = JSON.parse(data); 
       console.log(parsedConfig); 
       console.log(parsedConfig.foo); 
     } 
}); 

JSON文件:

{ 
     "foo": "bar" 
} 

輸出:

$ node test_node3.js 
{ 
     "foo": "bar" 
} 

{ foo: 'bar' } 
bar 

這是節點0.4.10,但我敢肯定它應該對所有節點版本。

那麼,爲什麼你的數據是空的?在這種情況下,你應該檢查err(如我的)併發布輸出(如果有的話)。如果你沒有錯誤,你可以在github上填寫一個bug

+0

錯誤中沒有任何內容。它認爲它已經工作,但沒有返回任何數據。也許我應該提交一個bug,但我不知道如何重新創建問題。我真的沒有什麼特別的,它可能是Mac的東西嗎? – Olical

+0

如果您無法重新創建它,則無法填充錯誤。它可能與mac有關。 – malletjo