Onestay Onestay - 1 month ago 7
Node.js Question

Doing something after a file has been downloaded

I'm kinda new to programming in general. My problem is that I want to download a file and after that do something.

Danbooru.search(tag, function (err, data) { //search for a random image with the given tag
data.random() //selects a random image with the given tag
.getLarge() //get's a link to the image
.pipe(require('fs').createWriteStream('random.jpg')); //downloads the image
});


now I want to do a console.log after the file has been downloaded. I don't want to work with setTimeout since the files will take a diffrent time to download.

Thanks for the help.

Answer

See if this works for you. Just saving the request to a variable and checking for the finish event on it.

Danbooru.search(tag, function (err, data) { 
        var stream = data.random() 
            .getLarge() 
            .pipe(require('fs').createWriteStream('random.jpg'));

            stream.on('finish', function() { console.log('file downloaded'); });
        });
Comments