How to use async/await on blob service. I am trying download and zip folder and hence want to wait untill download completes, so that I can go ahead and zip that file.but due to async behaviour sometime function misbehaveing.
Latest code:
const blobServiceClient = BlobServiceClient.fromConnectionString("connect string");
const containerClient = blobServiceClient.getContainerClient(containerName);
for await (const blob of containerClient.listBlobsFlat({ prefix: path })) {
if (fs.existsSync(fileUploadPath)) {
var sourceFilePath = fileUploadPath + '/' + project.id + '/' + blob.name;
if (!fs.existsSync(sourceFilePath)) {
fs.mkdir(require('path').dirname(sourceFilePath), { recursive: true }, async(err) => {
if (err) {
console.log("Failed to mkdir:" + err);
}
console.log(blob.name)
await containerClient.getBlobClient(blob.name).downloadToFile(sourceFilePath,0,undefined);
});
}
} else{
console.log('downloads folder does not configures!')
}
I have a couple of doubts here,
Using the latest version of the Azure Storage Blob SDK, you could convert your existing code to something like that:
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");
const account = "<account>";
const accountKey = "<accountkey>";
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
const blobServiceClient = new BlobServiceClient(
`https://${account}.blob.core.windows.net`,
sharedKeyCredential
);
const containerName = '<container name>';
const path = '<prefix>';
async function download() {
var containerClient = blobServiceClient.getContainerClient(containerName);
for await (const blob of containerClient.listBlobsFlat({ prefix: path })) {
await containerClient.getBlobClient(blob.name)
.downloadToFile(`./${blob.name}`);
}
}
download()
.then(() => console.log('Done'))
.catch((ex) => console.log(ex.message));