2012-08-07 33 views
0

隆泰听众,第一次来电者:-)从发送的NodeJS的照片作为JSON阵列

我是新来的NodeJS和javascript和我在努力环绕事件&回调模型我的头。

我的目标是:将照片(名称,宽度,高度,Exif数据)返回为JSON。这是需要的,以便我的应用程序可以使用JSON阵列的图片工作。

情况:我的代码似乎工作,但事情没有按照我想要的顺序运行。我期待将每张图片的JSON流式传输到HTTP响应,但是我的控制台日志记录显示事情并非按照所需顺序进行,我怀疑res.end()过早调用。这意味着我的Web请求在响应中没有任何内容。

相关的代码:

fs.readdir(readDir, function (err, files) { 
    var picsInfo; 
    if (err) res.writeHead(500, err.message); 
    else if (!files.length) res.writeHead(404); 
    else { 
     res.writeHead(200, { 'Content-Type': 'application/json' }); 
      files.forEach(function(file) { 
     console.log('easyimage'); 
     easyimg.info(readDir + '/' + file, function(err, stdout, stderr) { 
      if (err) throw err; 
      console.log(JSON.stringify(stdout)); 
      res.write(JSON.stringify(stdout)); 
     }); 
     }); 
    } 
    res.end(); 
}); 

在我的控制台我看到的输出显示事情不是为了(我希望每一张照片被发送到RES):

easyimage 
easyimage 
easyimage 
easyimage 
easyimage 
easyimage 
easyimage 
easyimage 
easyimage 
easyimage 
{"type":"JPEG","depth":"8","width":"933","height":"1400","size":"532365B","name":"6.jpg"} 
{"type":"JPEG","depth":"8","width":"1400","height":"933","size":"318134B","name":"3.jpg"} 
{"type":"JPEG","depth":"8","width":"1400","height":"933","size":"310927B","name":"10.jpg"} 
{"type":"JPEG","depth":"8","width":"933","height":"1400","size":"258928B","name":"1.jpg"} 
req.method=GET... 
{"type":"JPEG","depth":"8","width":"1400","height":"928","size":"384475B","name":"7.jpg"} 
{"type":"JPEG","depth":"8","width":"933","height":"1400","size":"469711B","name":"4.jpg"} 
{"type":"JPEG","depth":"8","width":"1400","height":"933","size":"392666B","name":"2.jpg"} 
{"type":"JPEG","depth":"8","width":"1400","height":"933","size":"354468B","name":"5.jpg"} 
{"type":"JPEG","depth":"8","width":"1400","height":"933","size":"438143B","name":"9.jpg"} 
{"type":"JPEG","depth":"8","width":"933","height":"1400","size":"304939B","name":"8.jpg"} 

我我尝试过使用一些我发现的例子(例如http://blog.nakedjavascript.com/going-evented-with-nodejs,但是我认为我只是在事件/回调模型方面缺少某些关键的东西,任何指针或帮助都将非常感谢。另外,如果我的方法(例如发送JSON的水库等)是愚蠢的或次优我还喜欢关于wh的一些提示可能是最好的。

在此先感谢提供任何指针&的帮助!

回答

0

OK,我不能运行的代码,因此它可能需要一些调整:

​​

有什么问题与您的代码?

  • 正如我刚才所说,res.end()是异步调用立即使用,因为easyimg.info答案。
  • 您对每个文件都致电easyimg.info,但不能保证响应将按顺序到达。看到精彩的async库(npm install async)。
  • 当您使用回调返回错误时,请确保您返回。始终使用图案return cb(err)
+0

感谢您的快速帮助,Laurent!这有所帮助,但它仍然没有像我预期的那样工作。我做了你建议的调整,我得到了一张照片的JSON输出到浏览器(即请求)。但是,其他照片'JSON不会通过。在我看来,res.end()过早被调用(即第一张照片的JSON被发送到响应之后)。 – 2012-08-07 21:06:06

+0

好的,我看到了问题,我正在更新我的答案。 – 2012-08-07 21:09:16

+0

我将在今晚晚些时候深入研究,并会让你知道它是如何发生的。乍一看,我并不关注如何继续在代码中使用easyimgae包(https://github.com/hacksparrow/node-easyimage)。我需要将它变成一个单独的函数吗?另外,我是否需要在此代码之前编写HTTP标头? – 2012-08-07 21:51:29