0

长期听众,第一次来电:-)

我是 nodejs 和 javascript 的新手,我正在努力解决事件和回调模型。

我的目标:以 JSON 格式返回照片数组(名称、宽度、高度、exif 数据)。这是必要的,这样我的应用程序就可以使用 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 到 res 等)是愚蠢的或次优的,我也会喜欢一些关于什么可能是最好的提示。

提前感谢您的任何指示和帮助!

4

1 回答 1

0

好的,我无法运行代码,因此可能需要一些调整:

fs.readdir(readDir, function(err, files) {
    var filesPath = files.map(function(file) {
      return readDir + '/' + file;
    });

    async.map(filesPath, easyimg.info, function(err, json) {
        if(err)
            return res.end(500, err.message);

        res.end(JSON.stringify(json));
    });
});

你的代码有什么问题?

  • 正如我之前所说,res.end()因为easyimg.info异步回答而立即被调用。
  • 您调用easyimg.info每个文件,但不能保证响应会按顺序到达。查看精彩的异步库 ( npm install async)。
  • 当您通过回调返回错误时,请确保您也返回。始终使用该模式return cb(err)
于 2012-08-07T20:55:46.323 回答