Search code examples
azure-blob-storageazure-node-sdk

How to Copy a blob in azure to another container with node sdk


I am trying to copy a blob in one container to another storage account in azure.

I am using @azure/storage-blob 12.0.0 but I cannot figure out how to copy a blob to another container without downloading it.

Maybe someone can help and post a quick example.

Stefan


Solution

  • If you want to copy blob with nodejs sdk @azure/storage-blob, you can use the method BlobClient.beginCopyFromURL to implement it. For more details, please refer to the document.

    For example(copy blob from one container to another container in same storage account)

    const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");
    
    async function copy(){
    
        const account = "blobstorage0516";
        const accountKey=""
        const cert = new StorageSharedKeyCredential(account,accountKey)
        const blobServiceClient = new BlobServiceClient(
          `https://${account}.blob.core.windows.net`,
          cert
        );
        
        const sourceContainer=blobServiceClient.getContainerClient("test")
        const desContainer=blobServiceClient.getContainerClient("copy")
        //if the desContainer does not exist, please run the following code
        await desContainer.create()
        
        //copy blob
        const sourceBlob=sourceContainer.getBlobClient("emp.txt");
        const desBlob=desContainer.getBlobClient(sourceBlob.name)
        const response =await desBlob.beginCopyFromURL(sourceBlob.url);
        const result = (await response.pollUntilDone())
        console.log(result._response.status)
        console.log(result.copyStatus)
    }
    
    copy()
    

    enter image description here