What is the basic difference between these two operations ?
someReadStream.pipe(fs.createWriteStream('foo.png'));
vS
someReadStream.on('data',function(chunk) { blob += chunk } ); someReadStream.on('end', function() { fs.writeFile('foo.png',blob) });
When using request library for scraping , i can save pics(png,bmp) etc.. only with the former method and with the latter one there is same gibbersh(binary) data but image doesnt render .
How are they different ?
When you are working with streams in node.js you shall prefer piping them.
According to Node Docs 'data' events emits either buffer (by default) or string (if encoding was set).
When you are working with text streams you can use 'data' event to concatenate all chunks of data together. Then you'll be able to work with your data as with regular string.
But when you working with binary data it's not so simple, because you'll receive buffers. To concatenate buffers you shall use special methods like Buffer.concat. So, it's possible to use such approach for binary streams but it not worth the pain.
Update
If you want to do it hard way, try the following code:
var buffers = [];
readstrm.on('data', function(chunk) {
buffers.push(chunk);
});
readstrm.on('end', function() {
fs.writeFile('foo.png', Buffer.concat(buffers));
});
I could't test is, but it looks ok.
It's easy to notice when something went wrong by checking file size.