Callback function after image has downloaded

saeed picture saeed · Sep 16, 2012 · Viewed 9k times · Source

I'm trying to save an image download with the request module. With this

request('http://google.com/images/logos/ps_logo2.png').pipe(fs.createWriteStream('doodle.png')); 

It works fine. But I want to be able to do something else after the image has been completely downloaded. How can provide a callback function to fs.createWriteStream ?

Answer

Charlie Key picture Charlie Key · Sep 16, 2012

You want to create the stream ahead of time and then do something on the close event.

var picStream = fs.createWriteStream('doodle.png');
picStream.on('close', function() {
  console.log('file done');
});
request('http://google.com/images/logos/ps_logo2.png').pipe(picStream); 

This should do it.