Question

I am downloading several images and want to to access the files directly after thex have been written. I wait for the end event and then i try to access the files. Sometimes this fails because a file doesn't seem to have been written.

If i comment the accessing of the files, the images get all downloaded and saved as expected.

How can i access my files after they have been downloaded? Do i need to wait for another event?

// 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
    });
});
Was it helpful?

Solution

image_file.end() is not atomic, you need to wait for the callback to be sure that it has been written.

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

or you can watch for the finish on the writeStream

image_file.on('finish', callback)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top