Here is the code:

var fs = require('fs') var request = require('request'); request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) 

It saves the data (file) received by reference to the file .. :)

My questions are:

  1. How to finish writing data to the file immediately read them again using createReadStream ??

  2. How to track or wait that the data in the file is already 100% all written before reading ??

  3. Is it possible to hang a promise on this request or pipe? or otherwise rewrite it?

  4. Suppose there are a lot of links from which the data will be written to files in a loop - And then how can I immediately read them again if the loop is asynchronous ??

1 answer 1

You can wait for completion by processing the finish event:

 request('http://google.com/doodle.png') .pipe(fs.createWriteStream('doodle.png')) .on("finish", ...); 

But there is a problem - pipe does not close the output stream when there is a read error and does not forward it further, therefore the error must be processed separately!

Error handling is something like this:

 var source = request('http://google.com/doodle.png'); var dest = source.pipe(fs.createWriteStream('doodle.png')) var promise = new Promise((resolve, reject) => { dest.on('finish', resolve); source.on('error', reject); dest.on('error', reject); }).catch(e => new Promise((_, reject) => { dest.end(() => { fs.unlink('doodle.png', () => reject(e)); }); })); 

If the undeleted files are not deleted, then the code will, of course, be easier - but the underextended files usually lead to incomprehensible glitches.