Reputation: 9054
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);
});
}
Upvotes: 2
Views: 6620
Reputation: 469
Please try BlockBlobClient.downloadToFile()
method
const response = await blockBlobClient.downloadToFile("filePath");
Upvotes: 2
Reputation: 136196
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);
});
}
Upvotes: 1