1
votes

I have node.js Application with Frontend in Angular, I need to upload and download files to Azure blob/azure storage

I have followed instructions given here: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/storage/storage-blob/samples/typescript/src/basic.ts

now when I download it reads the image or file in readable stream, how can I download the file from azure blob

below is my code which list the blobs reads to readable stream

const { BlobServiceClient, StorageSharedKeyCredential, BlobDownloadResponseModel } = require('@azure/storage-blob');

const uuidv1 = require('uuid/v1');

async ListBlob(req,res){
    const blobServiceClient = await BlobServiceClient.fromConnectionString(this.AZURE_STORAGE_CONNECTION_STRING);
    const container = blobServiceClient.getContainerClient('mycontainer');
    const containerClient = await blobServiceClient.getContainerClient(container.containerName);
    let temp = Array();
    // List the blob(s) in the container.
    for await (const blob of containerClient.listBlobsFlat()) {
        temp.push(blob.name);
    }
    const blockBlobClient = containerClient.getBlockBlobClient(temp[2]);
    const downloadBlockBlobResponse = await blockBlobClient.download(0);
    let result = await this.streamToString(downloadBlockBlobResponse.readableStreamBody!);
    res.send(result);

}

async streamToString(readableStream) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    readableStream.on("data", (data) => {
      chunks.push(data.toString());
    });
    readableStream.on("end", () => {
      resolve(chunks.join(""));
    });
    readableStream.on("error", reject);
  });
}
2
Is there an error you're running into with the code that you have written? Your code looks fine to me.Gaurav Mantri
How can I download the file ?, now it reads the file as a readable streamMJ X
Or do you know how to convert this readable stream to actual file and download it, I don't know to much about it, if you could provide details I would appreciateMJ X
Added an answer (untested code though). HTH.Gaurav Mantri

2 Answers

2
votes

Please try BlockBlobClient.downloadToFile() method

  const response = await blockBlobClient.downloadToFile("filePath");
0
votes

If your objective is to write the stream to a local file, then all you need to do is read the stream as buffer and save that in a file using fs module in Node.

Essentially you can try something like this:

const fs = require('fs');

async streamToLocalFile(readableStream) {
  return new Promise((resolve, reject) => {
    let buffer = Buffer.from([]);
    readableStream.on("data", (data) => {
        buffer = Buffer.concat([buffer, data], buffer.length+data.length);//Add the data read to the existing buffer.
    });
    readableStream.on("end", () => {
        fs.writeFileSync('your file path', buffer);//Write buffer to local file.
        resolve('your file path);//Return that file path.  
    });
    readableStream.on("error", reject);
  });
}