tomconte
tomconte

Reputation: 1020

How to stream a Windows Azure Blob to the client using Node.js?

I would like to send a Windows Azure Blob (an image) directly to the client ; I am trying this :

    blobService.getBlobToStream('images', req.url, res, function(err, blob) {
    if (!err) {
        res.writeHead(200, { 'Content-Type': blob.contentType });
    } else {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(err);
    }
});

I am trying to pipe the Blob stream directly to the response stream ; should this work ? In Firefox, I get a message : "The image cannot be displayed because it contains errors". Looking at Firebug, the size of the image is 0.

Upvotes: 3

Views: 4479

Answers (2)

Benjamin Castor
Benjamin Castor

Reputation: 244

With [email protected] I was getting errors about writing to the response after it was finalized. I also noticed that getBlobToStream handles the content type automatically.

const storage = require('azure-storage');
const blobService = storage.createBlobService(azureStorage.account, azureStorage.key); // if you want aren't using the same azure env vars

blobService.getBlobToStream(config.switchConfigStorage.container, 'image.png', res, function(error, blob){
  if(!error){ // blob retrieved
    console.log(blob); // good for debugging and possibly more processing
    res.end(); // no need to writeHead
  }else{
    console.log(error);
    res.end();
  }
});

Upvotes: 0

Richard Astbury
Richard Astbury

Reputation: 2353

This seems to work prefectly for me (if this is any help?):

var azure = require('azure');
var http = require('http');
http.createServer(function (req, res) {
    var blobService = azure.createBlobService("xxx", "yyy", "blob.core.windows.net").withFilter(new azure.ExponentialRetryPolicyFilter());
    blobService.getBlobToStream('container', 'image.png', res, function(error){
        if(!error){
            res.writeHead(200, {'Content-Type': 'image/png'});
            res.end();
        }
        else
        {
            console.log('error');
            console.log(error);
            res.end();
        }
    });
}).listen(8080, "127.0.0.1");

Update

Just figured it out. req.url will have a leading slash (/). Which I'm guessing will not match your image filename.

Upvotes: 6

Related Questions