【发布时间】:2014-05-08 23:35:49
【问题描述】:
我正在下载几张图片,并希望在它们被写入后直接访问这些文件。我等待结束事件,然后尝试访问文件。 有时这会失败,因为似乎没有写入文件。
如果我对文件的访问进行评论,则图像将全部下载并按预期保存。
我如何在下载文件后访问我的文件?我需要等待另一个事件吗?
// 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
});
});
【问题讨论】:
标签: javascript node.js fs