我有一個相當簡單的腳本,它嘗試讀取並解析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
它可能是權限或所有權嗎?我已經嘗試了許可集755
和777
無濟於事。
我正在運行節點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.'));
}
});
我在代碼中看不到utf8。這是實際的代碼? – thejh
對不起,不是,我剛剛輸入了一個副本,我會添加UTF-8。 – Olical
@thejs我添加了一段我的實際代碼。我可以向你保證'file'變量是一個字符串並且轉到正確的文件。 – Olical