我有一个相当简单的脚本,它尝试读取并解析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