Last time we talked about creating Azure blobs.
This time we’ll turn things around and talk about downloading Azure blobs.
Account Connection Boilerplate
As stated in the previous post, to work with blob storage, you first need to create a client instance.
To avoid duplicating code over and over, we’ll do that once here, and assume it in the other code samples.
To download a blob to a stream, use the getBlobToStream method.
123456789101112131415
// For simplicity, assume getSomeStream returns a writable streamvarmyStream=getSomeStream();varblobName='my-awesome-stream-blob';blobService.getBlobToStream(containerName,blobName,myStream,function(err,blob){if(err){console.error("Couldn't download blob %s",blobName);console.error(err);}else{console.log("Sucessfully downloaded blob %s",blobName);}});
You can also integrate with a web server to enable downloads from blob storage.
This is powerfull when combined with the getBlobProperties method.
In the following example, we use the createReadStream method so we can easily pipe the stream to the server response object.
12345678910111213141516
app.get('/download/:file',function(req,res){varfileName=req.params.file;blobService.getBlobProperties(containerName,fileName,function(err,properties,status){if(err){res.send(502,"Error fetching file: %s",err.message);}elseif(!status.isSuccessful){res.send(404,"The file %s does not exist",fileName);}else{res.header('Content-Type',properties.contentType);blobService.createReadStream(containerName,fileName).pipe(res);}});});
Conclusion
In this post we covered how to check whether a blob exists, and how to download the blob.
In the next post, we’ll cover how to list containers and blobs.
I am now accepting new clients for part-time consulting and software development projects.
Learn more