Nodejs:将文件写入hd后访问文件会产生错误。为什么?

时间:2014-05-08 15:23:45

标签: javascript node.js fs

我正在下载几张图片,并希望在写完这些图片后直接访问这些文件。我等待结束事件,然后我尝试访问文件。 有时这会失败,因为文件似乎没有被写入。

如果我评论文件的访问,图像将按预期下载并保存。

如何在下载文件后访问我的文件?我需要等待另一个活动吗?

// id changes dynamically in loop
var tmp_file = os.tmpdir() + "/" + id + "_image_file.jpg";
http.get(image_url, function(response) {
    var image_file = fs.createWriteStream(tmp_file); 
    response.on('data', function(chunk) {
        image_file.write(chunk);
    }).on('end', function() {
    image_file.end();
        console.log("File written: " + image_file.path);

        // check filesize - it happens that the filesize is 0 by now
    var stats = fs.statSync(tmp_file);
    var fileSizeInBytes = stats["size"];

        // use imagemagick to process file which sometimes isn't written by now
        im.readMetadata(tmp_file, function(err, metadata){
        if (err) throw err; // throws error
    });
});

1 个答案:

答案 0 :(得分:1)

image_file.end()不是原子的,你需要等待回调以确保它已被写入。

image_file.end([chunk], [encoding], [callback])

或者您可以在writeStream上观看完成

image_file.on('finish', callback)