I have followed official documentation for downloading blobs, but it downloads blob with metadata and properties. What I need to do is download blob file as it is from azure storage to local file system with node js. Please note that my blob storage is private.
Below is the code I have as of now
const { BlobServiceClient } = require('@azure/storage-blob');
const { v1: uuidv1} = require('uuid');
async function main() {
console.log('Azure Blob storage v12 - JavaScript quickstart sample');
// Quick start code goes here
const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
const containerName = process.env.CONTAINER_NAME;
// Create the BlobServiceClient object which will be used to create a container client
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
// Get a reference to a container
const containerClient = blobServiceClient.getContainerClient(containerName);
const blockBlobClient = containerClient.getBlockBlobClient(process.env.BLOB_NAME);
const downloadBlockBlobResponse = await blockBlobClient.download(0);
console.log('\nDownloaded blob content...');
console.log('\t', await streamToString(downloadBlockBlobResponse.readableStreamBody));
}
async function 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);
});
}
main().then(() => console.log('Done')).catch((ex) => console.log(ex.message))
To save the blob content to your local file system, you can simply use downloadToFile
method.
Essentially change the following line of code:
const downloadBlockBlobResponse = await blockBlobClient.download(0);
to
const downloadBlockBlobResponse = await blockBlobClient.downloadToFile('local-file-path');
You would also not need streamToString
method so you can safely delete that.