如何通过节点 js 从 azure 存储下载 blob 到本地存储?

How to download blobs from azure storage via node js to local storage?

我已按照 official documentation 下载 blob,但它下载的是带有元数据和属性的 blob。我需要做的是使用节点 js 从 azure 存储下载 blob 文件到本地文件系统。 请注意我的 blob 存储是私有的。

下面是我目前的代码

    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))

要将 blob 内容保存到本地文件系统,只需使用 downloadToFile 方法即可。

基本上更改以下代码行:

const downloadBlockBlobResponse = await blockBlobClient.download(0);

const downloadBlockBlobResponse = await blockBlobClient.downloadToFile('local-file-path');

您也不需要 streamToString 方法,因此您可以安全地删除它。