Package version:

BlockBlobClient defines a set of operations applicable to block blobs.

Hierarchy (view full)

Constructors

  • Creates an instance of BlockBlobClient.

    Parameters

    • connectionString: string

      Account connection string or a SAS connection string of an Azure storage account. [ Note - Account connection string can only be used in NODE.JS runtime. ] Account connection string example - DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net SAS connection string example - BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString

    • containerName: string

      Container name.

    • blobName: string

      Blob name.

    • Optionaloptions: StoragePipelineOptions

      Optional. Options to configure the HTTP pipeline.

    Returns BlockBlobClient

  • Creates an instance of BlockBlobClient. This method accepts an encoded URL or non-encoded URL pointing to a block blob. Encoded URL string will NOT be escaped twice, only special characters in URL path will be escaped. If a blob name includes ? or %, blob name must be encoded in the URL.

    Parameters

    Returns BlockBlobClient

  • Creates an instance of BlockBlobClient. This method accepts an encoded URL or non-encoded URL pointing to a block blob. Encoded URL string will NOT be escaped twice, only special characters in URL path will be escaped. If a blob name includes ? or %, blob name must be encoded in the URL.

    Parameters

    Returns BlockBlobClient

Properties

accountName: string
credential: any

Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the @azure/identity package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used.

isHttps: boolean
storageClientContext: StorageClient

StorageClient is a reference to protocol layer operations entry, which is generated by AutoRest generator.

url: string

Encoded URL string value.

Accessors

  • get containerName(): string
  • The name of the storage container the blob is associated with.

    Returns string

  • get name(): string
  • The name of the blob.

    Returns string

Methods

  • Asynchronously copies a blob to a destination within the storage account. This method returns a long running operation poller that allows you to wait indefinitely until the copy is completed. You can also cancel a copy before it is completed by calling cancelOperation on the poller. Note that the onProgress callback will not be invoked if the operation completes in the first request, and attempting to cancel a completed copy will result in an error being thrown.

    In version 2012-02-12 and later, the source for a Copy Blob operation can be a committed blob in any Azure storage account. Beginning with version 2015-02-21, the source for a Copy Blob operation can be an Azure file in any Azure storage account. Only storage accounts created on or after June 7th, 2012 allow the Copy Blob operation to copy from another storage account.

    Parameters

    • copySource: string

      url to the source Azure Blob/File.

    • options: BlobBeginCopyFromURLOptions = {}

      Optional options to the Blob Start Copy From URL operation.

    Returns Promise<PollerLikeWithCancellation<PollOperationState<BlobBeginCopyFromURLResponse>, BlobBeginCopyFromURLResponse>>

    https://learn.microsoft.com/rest/api/storageservices/copy-blob

    import { BlobServiceClient } from "@azure/storage-blob";
    import { DefaultAzureCredential } from "@azure/identity";

    const account = "<account>";
    const blobServiceClient = new BlobServiceClient(
    `https://${account}.blob.core.windows.net`,
    new DefaultAzureCredential(),
    );

    const containerName = "<container name>";
    const blobName = "<blob name>";
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blobClient = containerClient.getBlobClient(blobName);

    // Example using automatic polling
    const automaticCopyPoller = await blobClient.beginCopyFromURL("url");
    const automaticResult = await automaticCopyPoller.pollUntilDone();

    // Example using manual polling
    const manualCopyPoller = await blobClient.beginCopyFromURL("url");
    while (!manualCopyPoller.isDone()) {
    await manualCopyPoller.poll();
    }
    const manualResult = manualCopyPoller.getResult();

    // Example using progress updates
    const progressUpdatesCopyPoller = await blobClient.beginCopyFromURL("url", {
    onProgress(state) {
    console.log(`Progress: ${state.copyProgress}`);
    },
    });
    const progressUpdatesResult = await progressUpdatesCopyPoller.pollUntilDone();

    // Example using a changing polling interval (default 15 seconds)
    const pollingIntervalCopyPoller = await blobClient.beginCopyFromURL("url", {
    intervalInMs: 1000, // poll blob every 1 second for copy progress
    });
    const pollingIntervalResult = await pollingIntervalCopyPoller.pollUntilDone();

    // Example using copy cancellation:
    const cancelCopyPoller = await blobClient.beginCopyFromURL("url");
    // cancel operation after starting it.
    try {
    await cancelCopyPoller.cancelOperation();
    // calls to get the result now throw PollerCancelledError
    cancelCopyPoller.getResult();
    } catch (err: any) {
    if (err.name === "PollerCancelledError") {
    console.log("The copy was cancelled.");
    }
    }
  • Reads or downloads a blob from the system, including its metadata and properties. You can also call Get Blob to read a snapshot.

    • In Node.js, data returns in a Readable stream readableStreamBody
    • In browsers, data returns in a promise blobBody

    Parameters

    • offset: number = 0

      From which position of the blob to download, greater than or equal to 0

    • Optionalcount: number

      How much data to be downloaded, greater than 0. Will download to the end when undefined

    • options: BlobDownloadOptions = {}

      Optional options to Blob Download operation.

      Example usage (Node.js):

      import { BlobServiceClient } from "@azure/storage-blob";
      import { DefaultAzureCredential } from "@azure/identity";

      const account = "<account>";
      const blobServiceClient = new BlobServiceClient(
      `https://${account}.blob.core.windows.net`,
      new DefaultAzureCredential(),
      );

      const containerName = "<container name>";
      const blobName = "<blob name>";
      const containerClient = blobServiceClient.getContainerClient(containerName);
      const blobClient = containerClient.getBlobClient(blobName);

      // Get blob content from position 0 to the end
      // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
      const downloadBlockBlobResponse = await blobClient.download();
      if (downloadBlockBlobResponse.readableStreamBody) {
      const downloaded = await streamToString(downloadBlockBlobResponse.readableStreamBody);
      console.log(`Downloaded blob content: ${downloaded}`);
      }

      async function streamToString(stream: NodeJS.ReadableStream): Promise<string> {
      const result = await new Promise<Buffer<ArrayBuffer>>((resolve, reject) => {
      const chunks: Buffer[] = [];
      stream.on("data", (data) => {
      chunks.push(Buffer.isBuffer(data) ? data : Buffer.from(data));
      });
      stream.on("end", () => {
      resolve(Buffer.concat(chunks));
      });
      stream.on("error", reject);
      });
      return result.toString();
      }

      Example usage (browser):

      import { BlobServiceClient } from "@azure/storage-blob";
      import { DefaultAzureCredential } from "@azure/identity";

      const account = "<account>";
      const blobServiceClient = new BlobServiceClient(
      `https://${account}.blob.core.windows.net`,
      new DefaultAzureCredential(),
      );

      const containerName = "<container name>";
      const blobName = "<blob name>";
      const containerClient = blobServiceClient.getContainerClient(containerName);
      const blobClient = containerClient.getBlobClient(blobName);

      // Get blob content from position 0 to the end
      // In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
      const downloadBlockBlobResponse = await blobClient.download();
      const blobBody = await downloadBlockBlobResponse.blobBody;
      if (blobBody) {
      const downloaded = await blobBody.text();
      console.log(`Downloaded blob content: ${downloaded}`);
      }

    Returns Promise<BlobDownloadResponseParsed>

  • ONLY AVAILABLE IN NODE.JS RUNTIME.

    Downloads an Azure Blob in parallel to a buffer. Offset and count are optional, downloads the entire blob if they are not provided.

    Warning: Buffers can only support files up to about one gigabyte on 32-bit systems or about two gigabytes on 64-bit systems due to limitations of Node.js/V8. For blobs larger than this size, consider downloadToFile.

    Parameters

    • Optionaloffset: number

      From which position of the block blob to download(in bytes)

    • Optionalcount: number

      How much data(in bytes) to be downloaded. Will download to the end when passing undefined

    • Optionaloptions: BlobDownloadToBufferOptions

      BlobDownloadToBufferOptions

    Returns Promise<Buffer>

  • ONLY AVAILABLE IN NODE.JS RUNTIME.

    Downloads an Azure Blob in parallel to a buffer. Offset and count are optional, downloads the entire blob if they are not provided.

    Warning: Buffers can only support files up to about one gigabyte on 32-bit systems or about two gigabytes on 64-bit systems due to limitations of Node.js/V8. For blobs larger than this size, consider downloadToFile.

    Parameters

    • buffer: Buffer

      Buffer to be fill, must have length larger than count

    • Optionaloffset: number

      From which position of the block blob to download(in bytes)

    • Optionalcount: number

      How much data(in bytes) to be downloaded. Will download to the end when passing undefined

    • Optionaloptions: BlobDownloadToBufferOptions

      BlobDownloadToBufferOptions

    Returns Promise<Buffer>

  • ONLY AVAILABLE IN NODE.JS RUNTIME.

    Downloads an Azure Blob to a local file. Fails if the the given file path already exits. Offset and count are optional, pass 0 and undefined respectively to download the entire blob.

    Parameters

    • filePath: string
    • offset: number = 0

      From which position of the block blob to download.

    • Optionalcount: number

      How much data to be downloaded. Will download to the end when passing undefined.

    • options: BlobDownloadOptions = {}

      Options to Blob download options.

    Returns Promise<BlobDownloadResponseParsed>

    The response data for blob download operation, but with readableStreamBody set to undefined since its content is already read and written into a local file at the specified path.

  • Returns true if the Azure blob resource represented by this client exists; false otherwise.

    NOTE: use this function with care since an existing blob might be deleted by other clients or applications. Vice versa new blobs might be added by other clients or applications after this function completes.

    Parameters

    Returns Promise<boolean>

  • ONLY AVAILABLE IN NODE.JS RUNTIME.

    Quick query for a JSON or CSV formatted blob.

    Example usage (Node.js):

    import { BlobServiceClient } from "@azure/storage-blob";
    import { DefaultAzureCredential } from "@azure/identity";

    const account = "<account>";
    const blobServiceClient = new BlobServiceClient(
    `https://${account}.blob.core.windows.net`,
    new DefaultAzureCredential(),
    );

    const containerName = "<container name>";
    const blobName = "<blob name>";
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);

    // Query and convert a blob to a string
    const queryBlockBlobResponse = await blockBlobClient.query("select from BlobStorage");
    if (queryBlockBlobResponse.readableStreamBody) {
    const downloadedBuffer = await streamToBuffer(queryBlockBlobResponse.readableStreamBody);
    const downloaded = downloadedBuffer.toString();
    console.log(`Query blob content: ${downloaded}`);
    }

    async function streamToBuffer(readableStream: NodeJS.ReadableStream): Promise<Buffer> {
    return new Promise((resolve, reject) => {
    const chunks: Buffer[] = [];
    readableStream.on("data", (data) => {
    chunks.push(data instanceof Buffer ? data : Buffer.from(data));
    });
    readableStream.on("end", () => {
    resolve(Buffer.concat(chunks));
    });
    readableStream.on("error", reject);
    });
    }

    Parameters

    Returns Promise<BlobDownloadResponseModel>

  • Sets tags on the underlying blob. A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. Valid tag key and value characters include lower and upper case letters, digits (0-9), space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_').

    Parameters

    Returns Promise<BlobSetTagsResponse>

  • Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported; the content of the existing blob is overwritten with the new content. To perform a partial update of a block blob's, use stageBlock and commitBlockList.

    This is a non-parallel uploading method, please use uploadFile, uploadStream or uploadBrowserData for better performance with concurrency uploading.

    Parameters

    • body: HttpRequestBody

      Blob, string, ArrayBuffer, ArrayBufferView or a function which returns a new Readable stream whose offset is from data source beginning.

    • contentLength: number

      Length of body in bytes. Use Buffer.byteLength() to calculate body length for a string including non non-Base64/Hex-encoded characters.

    • options: BlockBlobUploadOptions = {}

      Options to the Block Blob Upload operation.

    Returns Promise<BlockBlobUploadResponse>

    Response data for the Block Blob Upload operation.

    Example usage:

    import { BlobServiceClient } from "@azure/storage-blob";
    import { DefaultAzureCredential } from "@azure/identity";

    const account = "<account>";
    const blobServiceClient = new BlobServiceClient(
    `https://${account}.blob.core.windows.net`,
    new DefaultAzureCredential(),
    );

    const containerName = "<container name>";
    const blobName = "<blob name>";
    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);

    const content = "Hello world!";
    const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
  • ONLY AVAILABLE IN NODE.JS RUNTIME.

    Uploads a local file in blocks to a block blob.

    When file size lesser than or equal to 256MB, this method will use 1 upload call to finish the upload. Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList to commit the block list.

    Parameters

    Returns Promise<BlobUploadCommonResponse>

    Response data for the Blob Upload operation.

  • ONLY AVAILABLE IN NODE.JS RUNTIME.

    Uploads a Node.js Readable stream into block blob.

    PERFORMANCE IMPROVEMENT TIPS:

    • Input stream highWaterMark is better to set a same value with bufferSize parameter, which will avoid Buffer.concat() operations.

    Parameters

    • stream: Readable

      Node.js Readable stream

    • bufferSize: number = DEFAULT_BLOCK_BUFFER_SIZE_BYTES

      Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB

    • maxConcurrency: number = 5

      Max concurrency indicates the max number of buffers that can be allocated, positive correlation with max uploading concurrency. Default value is 5

    • options: BlockBlobUploadStreamOptions = {}

      Options to Upload Stream to Block Blob operation.

    Returns Promise<BlobUploadCommonResponse>

    Response data for the Blob Upload operation.

  • Creates a new BlockBlobClient object identical to the source but with the specified snapshot timestamp. Provide "" will remove the snapshot and return a URL to the base blob.

    Parameters

    • snapshot: string

      The snapshot timestamp.

    Returns BlockBlobClient

    A new BlockBlobClient object identical to the source but with the specified snapshot timestamp.

  • Creates a new BlobClient object pointing to a version of this blob. Provide "" will remove the versionId and return a Client to the base blob.

    Parameters

    • versionId: string

      The versionId.

    Returns BlobClient

    A new BlobClient object pointing to the version of this blob.