隆泰听众,第一次来电者:-)从发送的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的一些提示可能是最好的。
在此先感谢提供任何指针&的帮助!
感谢您的快速帮助,Laurent!这有所帮助,但它仍然没有像我预期的那样工作。我做了你建议的调整,我得到了一张照片的JSON输出到浏览器(即请求)。但是,其他照片'JSON不会通过。在我看来,res.end()过早被调用(即第一张照片的JSON被发送到响应之后)。 – 2012-08-07 21:06:06
好的,我看到了问题,我正在更新我的答案。 – 2012-08-07 21:09:16
我将在今晚晚些时候深入研究,并会让你知道它是如何发生的。乍一看,我并不关注如何继续在代码中使用easyimgae包(https://github.com/hacksparrow/node-easyimage)。我需要将它变成一个单独的函数吗?另外,我是否需要在此代码之前编写HTTP标头? – 2012-08-07 21:51:29