Search code examples
node.jsazureazure-storageazure-blob-storage

How to check for errors with Azure Blob createReadStream?


This code will work fine when the container and file exist, but there's no error checking:

function downloadFile(req, res){

  var container = 'aaa';
  var file = 'bbb';

  var stream = blobService.createReadStream(container, file);

  stream.pipe(res);

}

I'd like to add error checking code using stream events, but when I put the pipe into the data event it never gets called and the response never returns. If I put it into the end event the pipe sends a zero-length stream.

function downloadFile(req, res){

  var container = 'aaa';
  var file = 'bbb';

  var stream = blobService.createReadStream(container, file);

  stream.on('error', function(data){
    res.status(400).send({"message": "could not retrieve file"});
  });

  stream.on('data', function(data){
    stream.pipe(res);
  });

}

How can I hook this up properly so there's error checking with the stream?


Solution

  • You have set error event correctly, just remove the data event and simply use stream.pipe(res);. Things works on my side.

    I got outcomes opposite to yours, once I use data event, stream passes its content to data, so it has nothing left(zero-length stream) to write to res. And type of data is buffer(or string), has no method like pipe.

    End event will be emitted when there is no more data to be consumed from the stream, so it won't be called if we put the consumption operation inside.

    So there's no need to add event for stream.pipe(res); explicitly. Check nodejs stream events for more details.