2011-11-12 61 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