@azure/storage-blob package

Classes

Aborter

An aborter instance implements AbortSignal interface, can abort HTTP requests.

  • Call Aborter.none to create a new Aborter instance without timeout.
  • Call Aborter.timeout() to create a new Aborter instance with timeout.

For an existing instance aborter:

  • Call aborter.withTimeout() to create and return a child Aborter instance with timeout.
  • Call aborter.withValue(key, value) to create and return a child Aborter instance with key/value pair.
  • Call aborter.abort() to abort current instance and all children instances.
  • Call aborter.getValue(key) to search and get value with corresponding key from current aborter to all parents.

Example

// Abort without timeout await blockBlobURL.upload(Aborter.none, buf, buf.length);

Example

// Abort container create in 1000ms await blockBlobURL.upload(Aborter.timeout(1000), buf, buf.length);

Example

// Share aborter cross multiple operations in 30s // Upload the same data to 2 different data centers at the same time, abort another when any of them is finished const aborter = Aborter.timeout(30 * 1000); blockBlobURL1.upload(aborter, buf, buf.length).then(aborter.abort); blockBlobURL2.upload(aborter, buf, buf.length).then(aborter.abort);

Example

// Cascaded aborting // All operations can't take more than 30 seconds const aborter = Aborter.timeout(30 * 1000);

// Following 2 operations can't take more than 25 seconds await blockBlobURL.upload(aborter.withTimeout(25 * 1000), buf, buf.length); await blockBlobURL.upload(aborter.withTimeout(25 * 1000), buf, buf.length);

AccountSASPermissions

ONLY AVAILABLE IN NODE.JS RUNTIME. This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the values are set, this should be serialized with toString and set as the permissions field on an IAccountSASSignatureValues object. It is possible to construct the permissions string without this class, but the order of the permissions is particular and this class guarantees correctness.

AccountSASResourceTypes

ONLY AVAILABLE IN NODE.JS RUNTIME. This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value to true means that any SAS which uses these permissions will grant access to that resource type. Once all the values are set, this should be serialized with toString and set as the resources field on an IAccountSASSignatureValues object. It is possible to construct the resources string without this class, but the order of the resources is particular and this class guarantees correctness.

AccountSASServices

ONLY AVAILABLE IN NODE.JS RUNTIME. This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value to true means that any SAS which uses these permissions will grant access to that service. Once all the values are set, this should be serialized with toString and set as the services field on an IAccountSASSignatureValues object. It is possible to construct the services string without this class, but the order of the services is particular and this class guarantees correctness.

AppendBlobURL

AppendBlobURL defines a set of operations applicable to append blobs.

BatchDeleteRequest

A BatchDeleteRequest represents a batch delete request, which consists of one or more delete operations.

BatchRequest

A BatchRequest represents a based class for BatchDeleteRequest and BatchSetTierRequest.

BatchSetTierRequest

A BatchSetTierRequest represents a batch set tier request, which consists of one or more set tier operations.

InnerBatchRequest

Inner batch request class which is responsible for assembling and serializing sub requests. See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how request get assembled.

BatchResponseParser

Util class for parsing batch response.

BlobSASPermissions

ONLY AVAILABLE IN NODE.JS RUNTIME. This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the values are set, this should be serialized with toString and set as the permissions field on a IBlobSASSignatureValues object. It is possible to construct the permissions string without this class, but the order of the permissions is particular and this class guarantees correctness.

BlobURL

A BlobURL represents a URL to an Azure Storage blob; the blob may be a block blob, append blob, or page blob.

BlockBlobURL

BlockBlobURL defines a set of operations applicable to block blobs.

BrowserPolicyFactory

BrowserPolicyFactory is a factory class helping generating BrowserPolicy objects.

ContainerSASPermissions

This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the values are set, this should be serialized with toString and set as the permissions field on a IBlobSASSignatureValues object. It is possible to construct the permissions string without this class, but the order of the permissions is particular and this class guarantees correctness.

ContainerURL

A ContainerURL represents a URL to the Azure Storage container allowing you to manipulate its blobs.

KeepAlivePolicyFactory

KeepAlivePolicyFactory is a factory class helping generating KeepAlivePolicy objects.

LoggingPolicyFactory

LoggingPolicyFactory is a factory class helping generating LoggingPolicy objects.

PageBlobURL

PageBlobURL defines a set of operations applicable to page blobs.

Pipeline

A Pipeline class containing HTTP request policies. You can create a default Pipeline by calling StorageURL.newPipeline(). Or you can create a Pipeline with your own policies by the constructor of Pipeline. Refer to StorageURL.newPipeline() and provided policies as reference before implementing your customized Pipeline.

RetryPolicyFactory

RetryPolicyFactory is a factory class helping generating RetryPolicy objects.

SASQueryParameters

Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly by the user; it is only generated by the IAccountSASSignatureValues and IBlobSASSignatureValues types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should be taken here in case there are existing query parameters, which might affect the appropriate means of appending these query parameters). NOTE: Instances of this class are immutable.

ServiceURL

A ServiceURL represents a URL to the Azure Storage Blob service allowing you to manipulate blob containers.

StorageURL

A ServiceURL represents a based URL class for ServiceURL, ContainerURL and etc.

TelemetryPolicyFactory

TelemetryPolicyFactory is a factory class helping generating TelemetryPolicy objects.

UniqueRequestIDPolicyFactory

UniqueRequestIDPolicyFactory is a factory class helping generating UniqueRequestIDPolicy objects.

AnonymousCredential

AnonymousCredential provides a credentialPolicyCreator member used to create AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources or for use with Shared Access Signatures (SAS).

Credential

Credential is an abstract class for Azure Storage HTTP requests signing. This class will host an credentialPolicyCreator factory which generates CredentialPolicy.

SharedKeyCredential

ONLY AVAILABLE IN NODE.JS RUNTIME. SharedKeyCredential for account key authorization of Azure Storage service.

TokenCredential

TokenCredential is a Credential used to generate a TokenCredentialPolicy. Renew token by setting a new token string value to token property.

Example

const tokenCredential = new TokenCredential("token"); const pipeline = StorageURL.newPipeline(tokenCredential);

// List containers const serviceURL = new ServiceURL("https://mystorageaccount.blob.core.windows.net", pipeline);

// Set up a timer to refresh the token const timerID = setInterval(() => { // Update token by accessing to public tokenCredential.token tokenCredential.token = "updatedToken"; // WARNING: Timer must be manually stopped! It will forbid GC of tokenCredential if (shouldStop()) { clearInterval(timerID); } }, 60 * 60 * 1000); // Set an interval time before your token expired

UserDelegationKeyCredential

ONLY AVAILABLE IN NODE.JS RUNTIME. UserDelegationKeyCredential is only used for generation of user delegation SAS.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas

AppendBlob

Class representing a AppendBlob.

Blob

Class representing a Blob.

BlockBlob

Class representing a BlockBlob.

Container

Class representing a Container.

Directory

Class representing a Directory.

PageBlob

Class representing a PageBlob.

Service

Class representing a Service.

StorageClient
StorageClientContext
AnonymousCredentialPolicy

AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources or for use with Shared Access Signatures (SAS).

BrowserPolicy

BrowserPolicy will handle differences between Node.js and browser runtime, including:

  1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'. BrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL thus avoid the browser cache.

  2. Remove cookie header for security

  3. Remove content-length header to avoid browsers warning

CredentialPolicy

Credential policy used to sign HTTP(S) requests before sending. This is an abstract class.

KeepAlivePolicy

KeepAlivePolicy is a policy used to control keep alive settings for every request.

LoggingPolicy

LoggingPolicy is a policy used to log requests.

RetryPolicy

Retry policy with exponential retry and linear retry implemented.

SharedKeyCredentialPolicy

SharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key.

TelemetryPolicy

TelemetryPolicy is a policy used to tag user-agent header for every requests.

TokenCredentialPolicy

TokenCredentialPolicy is a policy used to sign HTTP request with a token. Such as an OAuth bearer token.

UniqueRequestIDPolicy

UniqueRequestIDPolicy generates an UUID as x-ms-request-id header value.

Batch

Batch provides basic parallel execution with concurrency limits. Will stop execute left operations when one of the executed operation throws an error. But Batch cannot cancel ongoing operations, you need to cancel them by yourself.

BufferScheduler

This class accepts a Node.js Readable stream as input, and keeps reading data from the stream into the internal buffer structure, until it reaches maxBuffers. Every available buffer will try to trigger outgoingHandler. The internal buffer structure includes an incoming buffer array, and a outgoing buffer array. The incoming buffer array includes the "empty" buffers can be filled with new incoming data. The outgoing array includes the filled buffers to be handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize.

NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING

NUM_OF_ALL_BUFFERS <= maxBuffers

PERFORMANCE IMPROVEMENT TIPS:

  1. Input stream highWaterMark is better to set a same value with bufferSize parameter, which will avoid Buffer.concat() operations.
  2. Parallelism should set a smaller value than maxBuffers, which is helpful to reduce the possibility when a outgoing handler waits for the stream data. in this situation, outgoing handlers are blocked. Outgoing queue shouldn't be empty.
Mutex

An async mutex lock.

RetriableReadableStream

ONLY AVAILABLE IN NODE.JS RUNTIME. A Node.js ReadableStream will internally retry when internal ReadableStream unexpected ends.

Interfaces

IAppendBlobAppendBlockFromURLOptions
IAppendBlobAppendBlockOptions
IAppendBlobCreateOptions
BatchSubRequest
BatchSubResponse
ParsedBatchResponse
IBlobAbortCopyFromURLOptions
IBlobAcquireLeaseOptions
IBlobBreakLeaseOptions
IBlobChangeLeaseOptions
IBlobCreateSnapshotOptions
IBlobDeleteOptions
IBlobDownloadOptions
IBlobGetPropertiesOptions
IBlobReleaseLeaseOptions
IBlobRenewLeaseOptions
IBlobSetHTTPHeadersOptions
IBlobSetMetadataOptions
IBlobSetTierOptions
IBlobStartCopyFromURLOptions
IBlobSyncCopyFromURLOptions
IBlockBlobCommitBlockListOptions
IBlockBlobGetBlockListOptions
IBlockBlobStageBlockFromURLOptions
IBlockBlobStageBlockOptions
IBlockBlobUploadOptions
IContainerAcquireLeaseOptions
IContainerBreakLeaseOptions
IContainerChangeLeaseOptions
IContainerCreateOptions
IContainerDeleteMethodOptions
IContainerGetAccessPolicyOptions
IContainerGetPropertiesOptions
IContainerListBlobsSegmentOptions
IContainerReleaseLeaseOptions
IContainerRenewLeaseOptions
IContainerSetAccessPolicyOptions
IContainerSetMetadataOptions
ISignedIdentifier
IAccountSASSignatureValues

ONLY AVAILABLE IN NODE.JS RUNTIME. IAccountSASSignatureValues is used to generate a Shared Access Signature (SAS) for an Azure Storage account. Once all the values here are set appropriately, call generateSASQueryParameters() to obtain a representation of the SAS which can actually be applied to blob urls. Note: that both this class and SASQueryParameters exist because the former is mutable and a logical representation while the latter is immutable and used to generate actual REST requests.

See https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 for more conceptual information on SAS

See https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas for descriptions of the parameters, including which are required

IBlobSASSignatureValues

ONLY AVAILABLE IN NODE.JS RUNTIME. IBlobSASSignatureValues is used to help generating Blob service SAS tokens for containers or blobs.

IIPRange

Allowed IP range for a SAS.

IRange

Range for Blob Service Operations.

See https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-the-range-header-for-blob-service-operations

IKeepAliveOptions

Interface of KeepAlivePolicy options.

IRequestLogOptions

RequestLogOptions configures the retry policy's behavior.

IPageBlobClearPagesOptions
IPageBlobCreateOptions
IPageBlobGetPageRangesDiffOptions
IPageBlobGetPageRangesOptions
IPageBlobResizeOptions
IPageBlobStartCopyIncrementalOptions
IPageBlobUpdateSequenceNumberOptions
IPageBlobUploadPagesFromURLOptions
IPageBlobUploadPagesOptions
IPipelineOptions

Option interface for Pipeline constructor.

IRetryOptions

Retry options interface.

IServiceListContainersSegmentOptions
UserDelegationKey

A user delegation key

INewPipelineOptions

Option interface for Pipeline.newPipeline method.

ITelemetryOptions

Interface of TelemetryPolicy options.

AccessPolicy

An Access policy

AppendBlobAppendBlockFromUrlHeaders

Defines headers for AppendBlockFromUrl operation.

AppendBlobAppendBlockFromUrlOptionalParams

Optional Parameters.

AppendBlobAppendBlockHeaders

Defines headers for AppendBlock operation.

AppendBlobAppendBlockOptionalParams

Optional Parameters.

AppendBlobCreateHeaders

Defines headers for Create operation.

AppendBlobCreateOptionalParams

Optional Parameters.

AppendPositionAccessConditions

Additional parameters for a set of operations, such as: AppendBlob_appendBlock, AppendBlob_appendBlockFromUrl.

BlobAbortCopyFromURLHeaders

Defines headers for AbortCopyFromURL operation.

BlobAbortCopyFromURLOptionalParams

Optional Parameters.

BlobAcquireLeaseHeaders

Defines headers for AcquireLease operation.

BlobAcquireLeaseOptionalParams

Optional Parameters.

BlobBreakLeaseHeaders

Defines headers for BreakLease operation.

BlobBreakLeaseOptionalParams

Optional Parameters.

BlobChangeLeaseHeaders

Defines headers for ChangeLease operation.

BlobChangeLeaseOptionalParams

Optional Parameters.

BlobCopyFromURLHeaders

Defines headers for CopyFromURL operation.

BlobCopyFromURLOptionalParams

Optional Parameters.

BlobCreateSnapshotHeaders

Defines headers for CreateSnapshot operation.

BlobCreateSnapshotOptionalParams

Optional Parameters.

BlobDeleteHeaders

Defines headers for Delete operation.

BlobDeleteMethodOptionalParams

Optional Parameters.

BlobDownloadHeaders

Defines headers for Download operation.

BlobDownloadOptionalParams

Optional Parameters.

BlobFlatListSegment

An interface representing BlobFlatListSegment.

BlobGetAccessControlHeaders

Defines headers for GetAccessControl operation.

BlobGetAccessControlOptionalParams

Optional Parameters.

BlobGetAccountInfoHeaders

Defines headers for GetAccountInfo operation.

BlobGetPropertiesHeaders

Defines headers for GetProperties operation.

BlobGetPropertiesOptionalParams

Optional Parameters.

BlobHTTPHeaders

Additional parameters for a set of operations.

BlobHierarchyListSegment

An interface representing BlobHierarchyListSegment.

BlobItem

An Azure Storage blob

BlobMetadata

An interface representing BlobMetadata.

BlobPrefix

An interface representing BlobPrefix.

BlobProperties

Properties of a blob

BlobReleaseLeaseHeaders

Defines headers for ReleaseLease operation.

BlobReleaseLeaseOptionalParams

Optional Parameters.

BlobRenameHeaders

Defines headers for Rename operation.

BlobRenameOptionalParams

Optional Parameters.

BlobRenewLeaseHeaders

Defines headers for RenewLease operation.

BlobRenewLeaseOptionalParams

Optional Parameters.

BlobSetAccessControlHeaders

Defines headers for SetAccessControl operation.

BlobSetAccessControlOptionalParams

Optional Parameters.

BlobSetHTTPHeadersHeaders

Defines headers for SetHTTPHeaders operation.

BlobSetHTTPHeadersOptionalParams

Optional Parameters.

BlobSetMetadataHeaders

Defines headers for SetMetadata operation.

BlobSetMetadataOptionalParams

Optional Parameters.

BlobSetTierHeaders

Defines headers for SetTier operation.

BlobSetTierOptionalParams

Optional Parameters.

BlobStartCopyFromURLHeaders

Defines headers for StartCopyFromURL operation.

BlobStartCopyFromURLOptionalParams

Optional Parameters.

BlobUndeleteHeaders

Defines headers for Undelete operation.

BlobUndeleteOptionalParams

Optional Parameters.

Block

Represents a single block in a block blob. It describes the block's ID and size.

BlockBlobCommitBlockListHeaders

Defines headers for CommitBlockList operation.

BlockBlobCommitBlockListOptionalParams

Optional Parameters.

BlockBlobGetBlockListHeaders

Defines headers for GetBlockList operation.

BlockBlobGetBlockListOptionalParams

Optional Parameters.

BlockBlobStageBlockFromURLHeaders

Defines headers for StageBlockFromURL operation.

BlockBlobStageBlockFromURLOptionalParams

Optional Parameters.

BlockBlobStageBlockHeaders

Defines headers for StageBlock operation.

BlockBlobStageBlockOptionalParams

Optional Parameters.

BlockBlobUploadHeaders

Defines headers for Upload operation.

BlockBlobUploadOptionalParams

Optional Parameters.

BlockList

An interface representing BlockList.

BlockLookupList

An interface representing BlockLookupList.

ClearRange

An interface representing ClearRange.

ContainerAcquireLeaseHeaders

Defines headers for AcquireLease operation.

ContainerAcquireLeaseOptionalParams

Optional Parameters.

ContainerBreakLeaseHeaders

Defines headers for BreakLease operation.

ContainerBreakLeaseOptionalParams

Optional Parameters.

ContainerChangeLeaseHeaders

Defines headers for ChangeLease operation.

ContainerChangeLeaseOptionalParams

Optional Parameters.

ContainerCreateHeaders

Defines headers for Create operation.

ContainerCreateOptionalParams

Optional Parameters.

ContainerDeleteHeaders

Defines headers for Delete operation.

ContainerDeleteMethodOptionalParams

Optional Parameters.

ContainerGetAccessPolicyHeaders

Defines headers for GetAccessPolicy operation.

ContainerGetAccessPolicyOptionalParams

Optional Parameters.

ContainerGetAccountInfoHeaders

Defines headers for GetAccountInfo operation.

ContainerGetPropertiesHeaders

Defines headers for GetProperties operation.

ContainerGetPropertiesOptionalParams

Optional Parameters.

ContainerItem

An Azure Storage container

ContainerListBlobFlatSegmentHeaders

Defines headers for ListBlobFlatSegment operation.

ContainerListBlobFlatSegmentOptionalParams

Optional Parameters.

ContainerListBlobHierarchySegmentHeaders

Defines headers for ListBlobHierarchySegment operation.

ContainerListBlobHierarchySegmentOptionalParams

Optional Parameters.

ContainerProperties

Properties of a container

ContainerReleaseLeaseHeaders

Defines headers for ReleaseLease operation.

ContainerReleaseLeaseOptionalParams

Optional Parameters.

ContainerRenewLeaseHeaders

Defines headers for RenewLease operation.

ContainerRenewLeaseOptionalParams

Optional Parameters.

ContainerSetAccessPolicyHeaders

Defines headers for SetAccessPolicy operation.

ContainerSetAccessPolicyOptionalParams

Optional Parameters.

ContainerSetMetadataHeaders

Defines headers for SetMetadata operation.

ContainerSetMetadataOptionalParams

Optional Parameters.

CorsRule

CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain

CpkInfo

Additional parameters for a set of operations.

DataLakeStorageError

An interface representing DataLakeStorageError.

DataLakeStorageErrorError

The service error response object.

DirectoryCreateHeaders

Defines headers for Create operation.

DirectoryCreateOptionalParams

Optional Parameters.

DirectoryDeleteHeaders

Defines headers for Delete operation.

DirectoryDeleteMethodOptionalParams

Optional Parameters.

DirectoryGetAccessControlHeaders

Defines headers for GetAccessControl operation.

DirectoryGetAccessControlOptionalParams

Optional Parameters.

DirectoryHttpHeaders

Additional parameters for a set of operations, such as: Directory_create, Directory_rename, Blob_rename.

DirectoryRenameHeaders

Defines headers for Rename operation.

DirectoryRenameOptionalParams

Optional Parameters.

DirectorySetAccessControlHeaders

Defines headers for SetAccessControl operation.

DirectorySetAccessControlOptionalParams

Optional Parameters.

GeoReplication

Geo-Replication information for the Secondary Storage Service

KeyInfo

Key information

LeaseAccessConditions

Additional parameters for a set of operations.

ListBlobsFlatSegmentResponse

An enumeration of blobs

ListBlobsHierarchySegmentResponse

An enumeration of blobs

ListContainersSegmentResponse

An enumeration of containers

Logging

Azure Analytics Logging settings.

Metrics

a summary of request statistics grouped by API in hour or minute aggregates for blobs

ModifiedAccessConditions

Additional parameters for a set of operations.

PageBlobClearPagesHeaders

Defines headers for ClearPages operation.

PageBlobClearPagesOptionalParams

Optional Parameters.

PageBlobCopyIncrementalHeaders

Defines headers for CopyIncremental operation.

PageBlobCopyIncrementalOptionalParams

Optional Parameters.

PageBlobCreateHeaders

Defines headers for Create operation.

PageBlobCreateOptionalParams

Optional Parameters.

PageBlobGetPageRangesDiffHeaders

Defines headers for GetPageRangesDiff operation.

PageBlobGetPageRangesDiffOptionalParams

Optional Parameters.

PageBlobGetPageRangesHeaders

Defines headers for GetPageRanges operation.

PageBlobGetPageRangesOptionalParams

Optional Parameters.

PageBlobResizeHeaders

Defines headers for Resize operation.

PageBlobResizeOptionalParams

Optional Parameters.

PageBlobUpdateSequenceNumberHeaders

Defines headers for UpdateSequenceNumber operation.

PageBlobUpdateSequenceNumberOptionalParams

Optional Parameters.

PageBlobUploadPagesFromURLHeaders

Defines headers for UploadPagesFromURL operation.

PageBlobUploadPagesFromURLOptionalParams

Optional Parameters.

PageBlobUploadPagesHeaders

Defines headers for UploadPages operation.

PageBlobUploadPagesOptionalParams

Optional Parameters.

PageList

the list of pages

PageRange

An interface representing PageRange.

RetentionPolicy

the retention policy which determines how long the associated data should persist

SequenceNumberAccessConditions

Additional parameters for a set of operations, such as: PageBlob_uploadPages, PageBlob_clearPages, PageBlob_uploadPagesFromURL.

ServiceGetAccountInfoHeaders

Defines headers for GetAccountInfo operation.

ServiceGetPropertiesHeaders

Defines headers for GetProperties operation.

ServiceGetPropertiesOptionalParams

Optional Parameters.

ServiceGetStatisticsHeaders

Defines headers for GetStatistics operation.

ServiceGetStatisticsOptionalParams

Optional Parameters.

ServiceGetUserDelegationKeyHeaders

Defines headers for GetUserDelegationKey operation.

ServiceGetUserDelegationKeyOptionalParams

Optional Parameters.

ServiceListContainersSegmentHeaders

Defines headers for ListContainersSegment operation.

ServiceListContainersSegmentOptionalParams

Optional Parameters.

ServiceSetPropertiesHeaders

Defines headers for SetProperties operation.

ServiceSetPropertiesOptionalParams

Optional Parameters.

ServiceSubmitBatchHeaders

Defines headers for SubmitBatch operation.

ServiceSubmitBatchOptionalParams

Optional Parameters.

SignedIdentifier

signed identifier

SourceModifiedAccessConditions

Additional parameters for a set of operations.

StaticWebsite

The properties that enable an account to host a static website

StorageClientOptions

An interface representing StorageClientOptions.

StorageError

An interface representing StorageError.

StorageServiceProperties

Storage Service Properties.

StorageServiceStats

Stats for the storage service.

IDownloadFromBlobOptions

Option interface for DownloadBlockBlobToBuffer.

IUploadToBlockBlobOptions

Option interface for uploadFileToBlockBlob and uploadSeekableStreamToBlockBlob.

IUploadStreamToBlockBlobOptions

Option interface for uploadStreamToBlockBlob.

IAppendBlobAccessConditions
IBlobAccessConditions
IContainerAccessConditions
IMetadata
IPageBlobAccessConditions
IRetriableReadableStreamOptions

Type Aliases

BlobDownloadResponse

Contains response data for the download operation.

ContainerGetAccessPolicyResponse

Contains response data for the getAccessPolicy operation.

ServiceGetUserDelegationKeyResponse

Contains response data for the getUserDelegationKey operation.

ServiceSubmitBatchResponse

Contains response data for the submitBatch operation.

CredentialPolicyCreator

A factory function that creates a new CredentialPolicy that uses the provided nextPolicy.

AccessTier

Defines values for AccessTier. Possible values include: 'P4', 'P6', 'P10', 'P15', 'P20', 'P30', 'P40', 'P50', 'P60', 'P70', 'P80', 'Hot', 'Cool', 'Archive'

AccountKind

Defines values for AccountKind. Possible values include: 'Storage', 'BlobStorage', 'StorageV2'

AppendBlobAppendBlockFromUrlResponse

Contains response data for the appendBlockFromUrl operation.

AppendBlobAppendBlockResponse

Contains response data for the appendBlock operation.

AppendBlobCreateResponse

Contains response data for the create operation.

ArchiveStatus

Defines values for ArchiveStatus. Possible values include: 'rehydrate-pending-to-hot', 'rehydrate-pending-to-cool'

BlobAbortCopyFromURLResponse

Contains response data for the abortCopyFromURL operation.

BlobAcquireLeaseResponse

Contains response data for the acquireLease operation.

BlobBreakLeaseResponse

Contains response data for the breakLease operation.

BlobChangeLeaseResponse

Contains response data for the changeLease operation.

BlobCopyFromURLResponse

Contains response data for the copyFromURL operation.

BlobCreateSnapshotResponse

Contains response data for the createSnapshot operation.

BlobDeleteResponse

Contains response data for the deleteMethod operation.

BlobGetAccessControlResponse

Contains response data for the getAccessControl operation.

BlobGetAccountInfoResponse

Contains response data for the getAccountInfo operation.

BlobGetPropertiesResponse

Contains response data for the getProperties operation.

BlobReleaseLeaseResponse

Contains response data for the releaseLease operation.

BlobRenameResponse

Contains response data for the rename operation.

BlobRenewLeaseResponse

Contains response data for the renewLease operation.

BlobSetAccessControlResponse

Contains response data for the setAccessControl operation.

BlobSetHTTPHeadersResponse

Contains response data for the setHTTPHeaders operation.

BlobSetMetadataResponse

Contains response data for the setMetadata operation.

BlobSetTierResponse

Contains response data for the setTier operation.

BlobStartCopyFromURLResponse

Contains response data for the startCopyFromURL operation.

BlobType

Defines values for BlobType. Possible values include: 'BlockBlob', 'PageBlob', 'AppendBlob'

BlobUndeleteResponse

Contains response data for the undelete operation.

BlockBlobCommitBlockListResponse

Contains response data for the commitBlockList operation.

BlockBlobGetBlockListResponse

Contains response data for the getBlockList operation.

BlockBlobStageBlockFromURLResponse

Contains response data for the stageBlockFromURL operation.

BlockBlobStageBlockResponse

Contains response data for the stageBlock operation.

BlockBlobUploadResponse

Contains response data for the upload operation.

BlockListType

Defines values for BlockListType. Possible values include: 'committed', 'uncommitted', 'all'

ContainerAcquireLeaseResponse

Contains response data for the acquireLease operation.

ContainerBreakLeaseResponse

Contains response data for the breakLease operation.

ContainerChangeLeaseResponse

Contains response data for the changeLease operation.

ContainerCreateResponse

Contains response data for the create operation.

ContainerDeleteResponse

Contains response data for the deleteMethod operation.

ContainerGetAccountInfoResponse

Contains response data for the getAccountInfo operation.

ContainerGetPropertiesResponse

Contains response data for the getProperties operation.

ContainerListBlobFlatSegmentResponse

Contains response data for the listBlobFlatSegment operation.

ContainerListBlobHierarchySegmentResponse

Contains response data for the listBlobHierarchySegment operation.

ContainerReleaseLeaseResponse

Contains response data for the releaseLease operation.

ContainerRenewLeaseResponse

Contains response data for the renewLease operation.

ContainerSetAccessPolicyResponse

Contains response data for the setAccessPolicy operation.

ContainerSetMetadataResponse

Contains response data for the setMetadata operation.

CopyStatusType

Defines values for CopyStatusType. Possible values include: 'pending', 'success', 'aborted', 'failed'

DeleteSnapshotsOptionType

Defines values for DeleteSnapshotsOptionType. Possible values include: 'include', 'only'

DirectoryCreateResponse

Contains response data for the create operation.

DirectoryDeleteResponse

Contains response data for the deleteMethod operation.

DirectoryGetAccessControlResponse

Contains response data for the getAccessControl operation.

DirectoryRenameResponse

Contains response data for the rename operation.

DirectorySetAccessControlResponse

Contains response data for the setAccessControl operation.

EncryptionAlgorithmType

Defines values for EncryptionAlgorithmType. Possible values include: 'AES256'

GeoReplicationStatusType

Defines values for GeoReplicationStatusType. Possible values include: 'live', 'bootstrap', 'unavailable'

LeaseDurationType

Defines values for LeaseDurationType. Possible values include: 'infinite', 'fixed'

LeaseStateType

Defines values for LeaseStateType. Possible values include: 'available', 'leased', 'expired', 'breaking', 'broken'

LeaseStatusType

Defines values for LeaseStatusType. Possible values include: 'locked', 'unlocked'

ListBlobsIncludeItem

Defines values for ListBlobsIncludeItem. Possible values include: 'copy', 'deleted', 'metadata', 'snapshots', 'uncommittedblobs'

ListContainersIncludeType

Defines values for ListContainersIncludeType. Possible values include: 'metadata'

PageBlobClearPagesResponse

Contains response data for the clearPages operation.

PageBlobCopyIncrementalResponse

Contains response data for the copyIncremental operation.

PageBlobCreateResponse

Contains response data for the create operation.

PageBlobGetPageRangesDiffResponse

Contains response data for the getPageRangesDiff operation.

PageBlobGetPageRangesResponse

Contains response data for the getPageRanges operation.

PageBlobResizeResponse

Contains response data for the resize operation.

PageBlobUpdateSequenceNumberResponse

Contains response data for the updateSequenceNumber operation.

PageBlobUploadPagesFromURLResponse

Contains response data for the uploadPagesFromURL operation.

PageBlobUploadPagesResponse

Contains response data for the uploadPages operation.

PathRenameMode

Defines values for PathRenameMode. Possible values include: 'legacy', 'posix'

PublicAccessType

Defines values for PublicAccessType. Possible values include: 'container', 'blob'

RehydratePriority

Defines values for RehydratePriority. Possible values include: 'High', 'Standard'

SequenceNumberActionType

Defines values for SequenceNumberActionType. Possible values include: 'max', 'update', 'increment'

ServiceGetAccountInfoResponse

Contains response data for the getAccountInfo operation.

ServiceGetPropertiesResponse

Contains response data for the getProperties operation.

ServiceGetStatisticsResponse

Contains response data for the getStatistics operation.

ServiceListContainersSegmentResponse

Contains response data for the listContainersSegment operation.

ServiceSetPropertiesResponse

Contains response data for the setProperties operation.

SkuName

Defines values for SkuName. Possible values include: 'Standard_LRS', 'Standard_GRS', 'Standard_RAGRS', 'Standard_ZRS', 'Premium_LRS'

StorageErrorCode

Defines values for StorageErrorCode. Possible values include: 'AccountAlreadyExists', 'AccountBeingCreated', 'AccountIsDisabled', 'AuthenticationFailed', 'AuthorizationFailure', 'ConditionHeadersNotSupported', 'ConditionNotMet', 'EmptyMetadataKey', 'InsufficientAccountPermissions', 'InternalError', 'InvalidAuthenticationInfo', 'InvalidHeaderValue', 'InvalidHttpVerb', 'InvalidInput', 'InvalidMd5', 'InvalidMetadata', 'InvalidQueryParameterValue', 'InvalidRange', 'InvalidResourceName', 'InvalidUri', 'InvalidXmlDocument', 'InvalidXmlNodeValue', 'Md5Mismatch', 'MetadataTooLarge', 'MissingContentLengthHeader', 'MissingRequiredQueryParameter', 'MissingRequiredHeader', 'MissingRequiredXmlNode', 'MultipleConditionHeadersNotSupported', 'OperationTimedOut', 'OutOfRangeInput', 'OutOfRangeQueryParameterValue', 'RequestBodyTooLarge', 'ResourceTypeMismatch', 'RequestUrlFailedToParse', 'ResourceAlreadyExists', 'ResourceNotFound', 'ServerBusy', 'UnsupportedHeader', 'UnsupportedXmlNode', 'UnsupportedQueryParameter', 'UnsupportedHttpVerb', 'AppendPositionConditionNotMet', 'BlobAlreadyExists', 'BlobNotFound', 'BlobOverwritten', 'BlobTierInadequateForContentLength', 'BlockCountExceedsLimit', 'BlockListTooLong', 'CannotChangeToLowerTier', 'CannotVerifyCopySource', 'ContainerAlreadyExists', 'ContainerBeingDeleted', 'ContainerDisabled', 'ContainerNotFound', 'ContentLengthLargerThanTierLimit', 'CopyAcrossAccountsNotSupported', 'CopyIdMismatch', 'FeatureVersionMismatch', 'IncrementalCopyBlobMismatch', 'IncrementalCopyOfEralierVersionSnapshotNotAllowed', 'IncrementalCopySourceMustBeSnapshot', 'InfiniteLeaseDurationRequired', 'InvalidBlobOrBlock', 'InvalidBlobTier', 'InvalidBlobType', 'InvalidBlockId', 'InvalidBlockList', 'InvalidOperation', 'InvalidPageRange', 'InvalidSourceBlobType', 'InvalidSourceBlobUrl', 'InvalidVersionForPageBlobOperation', 'LeaseAlreadyPresent', 'LeaseAlreadyBroken', 'LeaseIdMismatchWithBlobOperation', 'LeaseIdMismatchWithContainerOperation', 'LeaseIdMismatchWithLeaseOperation', 'LeaseIdMissing', 'LeaseIsBreakingAndCannotBeAcquired', 'LeaseIsBreakingAndCannotBeChanged', 'LeaseIsBrokenAndCannotBeRenewed', 'LeaseLost', 'LeaseNotPresentWithBlobOperation', 'LeaseNotPresentWithContainerOperation', 'LeaseNotPresentWithLeaseOperation', 'MaxBlobSizeConditionNotMet', 'NoPendingCopyOperation', 'OperationNotAllowedOnIncrementalCopyBlob', 'PendingCopyOperation', 'PreviousSnapshotCannotBeNewer', 'PreviousSnapshotNotFound', 'PreviousSnapshotOperationNotSupported', 'SequenceNumberConditionNotMet', 'SequenceNumberIncrementTooLarge', 'SnapshotCountExceeded', 'SnaphotOperationRateExceeded', 'SnapshotsPresent', 'SourceConditionNotMet', 'SystemInUse', 'TargetConditionNotMet', 'UnauthorizedBlobOverwrite', 'BlobBeingRehydrated', 'BlobArchived', 'BlobNotArchived'

SyncCopyStatusType

Defines values for SyncCopyStatusType. Possible values include: 'success'

BlobUploadCommonResponse

Type for uploadFileToBlockBlob, uploadStreamToBlockBlob and uploadBrowserDateToBlockBlob.

Operation

Operation is an async function to be executed and managed by Batch.

OutgoingHandler

OutgoingHandler is an async function triggered by BufferScheduler.

ReadableStreamGetter

Enums

SASProtocol

Protocols for generated SAS.

BlockBlobTier
PremiumPageBlobTier
RetryPolicyType

RetryPolicy types.

Functions

getBodyAsText(Models.ServiceSubmitBatchResponse)
utf8ByteLength(string)
generateAccountSASQueryParameters(IAccountSASSignatureValues, SharedKeyCredential)

ONLY AVAILABLE IN NODE.JS RUNTIME. Generates a SASQueryParameters object which contains all SAS query parameters needed to make an actual REST request.

See https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas

generateBlobSASQueryParameters(IBlobSASSignatureValues, SharedKeyCredential)

ONLY AVAILABLE IN NODE.JS RUNTIME. Creates an instance of SASQueryParameters.

Only accepts required settings needed to create a SAS. For optional settings please set corresponding properties directly, such as permissions, startTime and identifier.

WARNING: When identifier is not provided, permissions and expiryTime are required. You MUST assign value to identifier or expiryTime & permissions manually if you initial with this constructor.

Example

// Generate service level SAS for a container const containerSAS = generateBlobSASQueryParameters({ containerName, // Required permissions: ContainerSASPermissions.parse("racwdl").toString(), // Required startTime: new Date(), // Required expiryTime: tmr, // Optional. Date type ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional protocol: SASProtocol.HTTPSandHTTP, // Optional version: "2016-05-31" // Optional }, sharedKeyCredential // SharedKeyCredential ).toString();

Example

// Generate service level SAS for a container with identifier // startTime & permissions are optional when identifier is provided const identifier = "unique-id"; await containerURL.setAccessPolicy(Aborter.none, undefined, [ { accessPolicy: { expiry: tmr, // Date type permission: ContainerSASPermissions.parse("racwdl").toString(), start: now // Date type }, id: identifier } ]);

const containerSAS = generateBlobSASQueryParameters( { containerName, // Required identifier // Required }, sharedKeyCredential // SharedKeyCredential ).toString();

Example

// Generate service level SAS for a blob const blobSAS = generateBlobSASQueryParameters({ containerName, // Required blobName, // Required permissions: BlobSASPermissions.parse("racwd").toString(), // Required startTime: new Date(), // Required expiryTime: tmr, // Optional. Date type cacheControl: "cache-control-override", // Optional contentDisposition: "content-disposition-override", // Optional contentEncoding: "content-encoding-override", // Optional contentLanguage: "content-language-override", // Optional contentType: "content-type-override", // Optional ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional protocol: SASProtocol.HTTPSandHTTP, // Optional version: "2016-05-31" // Optional }, sharedKeyCredential // SharedKeyCredential ).toString();

generateBlobSASQueryParameters(IBlobSASSignatureValues, UserDelegationKey, string)

ONLY AVAILABLE IN NODE.JS RUNTIME. Creates an instance of SASQueryParameters. WARNING: identifier will be ignored when generating user delegation SAS, permissions and expiryTime are required.

Example

// Generate user delegation SAS for a container const userDelegationKey = await serviceURL.getUserDelegationKey(aborter, startTime, expiryTime); const containerSAS = generateBlobSASQueryParameters({ containerName, // Required permissions: ContainerSASPermissions.parse("racwdl").toString(), // Required startTime, // Required. Date type expiryTime, // Optional. Date type ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional protocol: SASProtocol.HTTPSandHTTP, // Optional version: "2018-11-09" // Must >= 2018-11-09 to generate user delegation SAS }, userDelegationKey, // UserDelegationKey accountName ).toString();

ipRangeToString(IIPRange)

Generate IPRange format string. For example: "8.8.8.8" or "1.1.1.1-255.255.255.255"

rangeToString(IRange)

Generate a range string. For example: "bytes=255-" or "bytes=0-511"

uploadBrowserDataToBlockBlob(Aborter, Blob | ArrayBuffer | ArrayBufferView, BlockBlobURL, IUploadToBlockBlobOptions)

ONLY AVAILABLE IN BROWSERS. Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob.

When buffer length <= 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.

downloadBlobToBuffer(Aborter, Buffer, BlobURL, number, undefined | number, IDownloadFromBlobOptions)

ONLY AVAILABLE IN NODE.JS RUNTIME. Downloads an Azure Blob in parallel to a buffer. Offset and count are optional, pass 0 for both to download the entire blob.

uploadFileToBlockBlob(Aborter, string, BlockBlobURL, IUploadToBlockBlobOptions)

ONLY AVAILABLE IN NODE.JS RUNTIME. Uploads a local file in blocks to a block blob.

When file size <= 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.

uploadStreamToBlockBlob(Aborter, Readable, BlockBlobURL, number, number, IUploadStreamToBlockBlobOptions)

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.
ensureCpkIfSpecified(CpkInfo | undefined, boolean)
toAccessTier(BlockBlobTier | PremiumPageBlobTier | string | undefined)
NewRetryPolicyFactory(IRetryOptions)

A factory method used to generated a RetryPolicy factory.

blobToArrayBuffer(Blob)

Convert a Browser Blob object into ArrayBuffer.

blobToString(Blob)

Convert a Browser Blob object into string.

appendToURLPath(string, string)

Append a string to URL path. Will remove duplicated "/" in front of the string when URL path ends with a "/".

base64decode(string)

Base64 decode.

base64encode(string)

Base64 encode.

delay(number, AbortSignalLike, Error)

Delay specified time interval.

escapeURLPath(string)

Reserved URL characters must be properly escaped for Storage services like Blob or File.

URL encode and escape strategy for JSv10 SDKs

When customers pass a URL string into XXXURL classes constrcutor, the URL string may already be URL encoded or not. But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XXXURL constructors.

Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK.

This is what legacy V2 SDK does, simple and works for most of the cases.

  • When customer URL string is "http://account.blob.core.windows.net/con/b:", SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
  • When customer URL string is "http://account.blob.core.windows.net/con/b%3A", SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created.

But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two:

Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters.

This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped.

  • When customer URL string is "http://account.blob.core.windows.net/con/b:", SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
  • When customer URL string is "http://account.blob.core.windows.net/con/b%3A", There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created.
  • When customer URL string is "http://account.blob.core.windows.net/con/b%253A", There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created.

This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. If customer needs to create a blob with "%" in it's blob name, use "%25" insead of "%". Just like above 3rd sample. And following URL strings are invalid:

  • "http://account.blob.core.windows.net/con/b%"
  • "http://account.blob.core.windows.net/con/b%2"
  • "http://account.blob.core.windows.net/con/b%G"

Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string.

Strategy for containerName, blobName or other specific XXXName parameters in methods such as BlobURL.fromContainerURL(containerURL, blobName)

We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL.

See https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata

See https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata

generateBlockID(string, number)

Generate a 64 bytes base64 block ID string.

getURLParameter(string, string)

Get URL parameter by name.

getURLPath(string)

Get URL path from an URL string.

getURLPathAndQuery(string)

Get URL path and query from an URL string.

getURLQueries(string)

Get URL query key value pairs from an URL string.

getURLScheme(string)

Get URL scheme from an URL string.

iEqual(string, string)

If two strings are equal when compared case insensitive.

padStart(string, number, undefined | string)

String.prototype.padStart()

setURLHost(string, string)

Set URL host.

setURLParameter(string, string, undefined | string)

Set URL parameter name and value. If name exists in URL parameters, old value will be replaced by name key. If not provide value, the parameter will be deleted.

truncatedISO8061Date(Date, undefined | false | true)

Rounds a date off to seconds.

streamToBuffer(ReadableStream, Buffer, number, number, undefined | string)

Reads a readable stream into buffer. Fill the buffer from offset to end.

streamToBuffer2(ReadableStream, Buffer, undefined | string)

Reads a readable stream into buffer entirely.

Function Details

getBodyAsText(Models.ServiceSubmitBatchResponse)

function getBodyAsText(batchResponse: Models.ServiceSubmitBatchResponse): Promise<string>

Parameters

batchResponse
Models.ServiceSubmitBatchResponse

Returns

Promise<string>

utf8ByteLength(string)

function utf8ByteLength(str: string): number

Parameters

str

string

Returns

number

generateAccountSASQueryParameters(IAccountSASSignatureValues, SharedKeyCredential)

ONLY AVAILABLE IN NODE.JS RUNTIME. Generates a SASQueryParameters object which contains all SAS query parameters needed to make an actual REST request.

See https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas

function generateAccountSASQueryParameters(accountSASSignatureValues: IAccountSASSignatureValues, sharedKeyCredential: SharedKeyCredential): SASQueryParameters

Parameters

accountSASSignatureValues
IAccountSASSignatureValues
sharedKeyCredential
SharedKeyCredential

Returns

generateBlobSASQueryParameters(IBlobSASSignatureValues, SharedKeyCredential)

ONLY AVAILABLE IN NODE.JS RUNTIME. Creates an instance of SASQueryParameters.

Only accepts required settings needed to create a SAS. For optional settings please set corresponding properties directly, such as permissions, startTime and identifier.

WARNING: When identifier is not provided, permissions and expiryTime are required. You MUST assign value to identifier or expiryTime & permissions manually if you initial with this constructor.

Example

// Generate service level SAS for a container const containerSAS = generateBlobSASQueryParameters({ containerName, // Required permissions: ContainerSASPermissions.parse("racwdl").toString(), // Required startTime: new Date(), // Required expiryTime: tmr, // Optional. Date type ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional protocol: SASProtocol.HTTPSandHTTP, // Optional version: "2016-05-31" // Optional }, sharedKeyCredential // SharedKeyCredential ).toString();

Example

// Generate service level SAS for a container with identifier // startTime & permissions are optional when identifier is provided const identifier = "unique-id"; await containerURL.setAccessPolicy(Aborter.none, undefined, [ { accessPolicy: { expiry: tmr, // Date type permission: ContainerSASPermissions.parse("racwdl").toString(), start: now // Date type }, id: identifier } ]);

const containerSAS = generateBlobSASQueryParameters( { containerName, // Required identifier // Required }, sharedKeyCredential // SharedKeyCredential ).toString();

Example

// Generate service level SAS for a blob const blobSAS = generateBlobSASQueryParameters({ containerName, // Required blobName, // Required permissions: BlobSASPermissions.parse("racwd").toString(), // Required startTime: new Date(), // Required expiryTime: tmr, // Optional. Date type cacheControl: "cache-control-override", // Optional contentDisposition: "content-disposition-override", // Optional contentEncoding: "content-encoding-override", // Optional contentLanguage: "content-language-override", // Optional contentType: "content-type-override", // Optional ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional protocol: SASProtocol.HTTPSandHTTP, // Optional version: "2016-05-31" // Optional }, sharedKeyCredential // SharedKeyCredential ).toString();

function generateBlobSASQueryParameters(blobSASSignatureValues: IBlobSASSignatureValues, sharedKeyCredential: SharedKeyCredential): SASQueryParameters

Parameters

blobSASSignatureValues
IBlobSASSignatureValues
sharedKeyCredential
SharedKeyCredential

Returns

generateBlobSASQueryParameters(IBlobSASSignatureValues, UserDelegationKey, string)

ONLY AVAILABLE IN NODE.JS RUNTIME. Creates an instance of SASQueryParameters. WARNING: identifier will be ignored when generating user delegation SAS, permissions and expiryTime are required.

Example

// Generate user delegation SAS for a container const userDelegationKey = await serviceURL.getUserDelegationKey(aborter, startTime, expiryTime); const containerSAS = generateBlobSASQueryParameters({ containerName, // Required permissions: ContainerSASPermissions.parse("racwdl").toString(), // Required startTime, // Required. Date type expiryTime, // Optional. Date type ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional protocol: SASProtocol.HTTPSandHTTP, // Optional version: "2018-11-09" // Must >= 2018-11-09 to generate user delegation SAS }, userDelegationKey, // UserDelegationKey accountName ).toString();

function generateBlobSASQueryParameters(blobSASSignatureValues: IBlobSASSignatureValues, userDelegationKey: UserDelegationKey, accountName: string): SASQueryParameters

Parameters

blobSASSignatureValues
IBlobSASSignatureValues
userDelegationKey
UserDelegationKey

Return value of ServiceURL.getUserDelegationKey()

accountName

string

Returns

ipRangeToString(IIPRange)

Generate IPRange format string. For example: "8.8.8.8" or "1.1.1.1-255.255.255.255"

function ipRangeToString(ipRange: IIPRange): string

Parameters

ipRange
IIPRange

Returns

string

rangeToString(IRange)

Generate a range string. For example: "bytes=255-" or "bytes=0-511"

function rangeToString(iRange: IRange): string

Parameters

iRange
IRange

Returns

string

uploadBrowserDataToBlockBlob(Aborter, Blob | ArrayBuffer | ArrayBufferView, BlockBlobURL, IUploadToBlockBlobOptions)

ONLY AVAILABLE IN BROWSERS. Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob.

When buffer length <= 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.

function uploadBrowserDataToBlockBlob(aborter: Aborter, browserData: Blob | ArrayBuffer | ArrayBufferView, blockBlobURL: BlockBlobURL, options?: IUploadToBlockBlobOptions): Promise<BlobUploadCommonResponse>

Parameters

aborter
Aborter

Create a new Aborter instance with Aborter.none or Aborter.timeout(), goto documents of Aborter for more examples about request cancellation

browserData

Blob | ArrayBuffer | ArrayBufferView

Blob, File, ArrayBuffer or ArrayBufferView

blockBlobURL
BlockBlobURL

Returns

downloadBlobToBuffer(Aborter, Buffer, BlobURL, number, undefined | number, IDownloadFromBlobOptions)

ONLY AVAILABLE IN NODE.JS RUNTIME. Downloads an Azure Blob in parallel to a buffer. Offset and count are optional, pass 0 for both to download the entire blob.

function downloadBlobToBuffer(aborter: Aborter, buffer: Buffer, blobURL: BlobURL, offset: number, count?: undefined | number, options?: IDownloadFromBlobOptions): Promise<void>

Parameters

aborter
Aborter

Create a new Aborter instance with Aborter.none or Aborter.timeout(), goto documents of Aborter for more examples about request cancellation

buffer

Buffer

Buffer to be fill, must have length larger than count

blobURL
BlobURL

A BlobURL object

offset

number

From which position of the block blob to download, in bytes

count

undefined | number

Returns

Promise<void>

uploadFileToBlockBlob(Aborter, string, BlockBlobURL, IUploadToBlockBlobOptions)

ONLY AVAILABLE IN NODE.JS RUNTIME. Uploads a local file in blocks to a block blob.

When file size <= 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.

function uploadFileToBlockBlob(aborter: Aborter, filePath: string, blockBlobURL: BlockBlobURL, options?: IUploadToBlockBlobOptions): Promise<BlobUploadCommonResponse>

Parameters

aborter
Aborter

Create a new Aborter instance with Aborter.none or Aborter.timeout(), goto documents of Aborter for more examples about request cancellation

filePath

string

Full path of local file

blockBlobURL
BlockBlobURL

BlockBlobURL

Returns

ICommonResponse

uploadStreamToBlockBlob(Aborter, Readable, BlockBlobURL, number, number, IUploadStreamToBlockBlobOptions)

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.
function uploadStreamToBlockBlob(aborter: Aborter, stream: Readable, blockBlobURL: BlockBlobURL, bufferSize: number, maxBuffers: number, options?: IUploadStreamToBlockBlobOptions): Promise<BlobUploadCommonResponse>

Parameters

aborter
Aborter

Create a new Aborter instance with Aborter.none or Aborter.timeout(), goto documents of Aborter for more examples about request cancellation

stream

Readable

Node.js Readable stream

blockBlobURL
BlockBlobURL

A BlockBlobURL instance

bufferSize

number

Size of every buffer allocated, also the block size in the uploaded block blob

maxBuffers

number

Max buffers will allocate during uploading, positive correlation with max uploading concurrency

Returns

ensureCpkIfSpecified(CpkInfo | undefined, boolean)

function ensureCpkIfSpecified(cpk: CpkInfo | undefined, isHttps: boolean)

Parameters

cpk

CpkInfo | undefined

isHttps

boolean

toAccessTier(BlockBlobTier | PremiumPageBlobTier | string | undefined)

function toAccessTier(tier: BlockBlobTier | PremiumPageBlobTier | string | undefined): Models.AccessTier | undefined

Parameters

tier

BlockBlobTier | PremiumPageBlobTier | string | undefined

Returns

Models.AccessTier | undefined

NewRetryPolicyFactory(IRetryOptions)

A factory method used to generated a RetryPolicy factory.

function NewRetryPolicyFactory(retryOptions?: IRetryOptions): RequestPolicyFactory

Parameters

retryOptions
IRetryOptions

Returns

RequestPolicyFactory

blobToArrayBuffer(Blob)

Convert a Browser Blob object into ArrayBuffer.

function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer>

Parameters

blob

Blob

Returns

Promise<ArrayBuffer>

blobToString(Blob)

Convert a Browser Blob object into string.

function blobToString(blob: Blob): Promise<string>

Parameters

blob

Blob

Returns

Promise<string>

appendToURLPath(string, string)

Append a string to URL path. Will remove duplicated "/" in front of the string when URL path ends with a "/".

function appendToURLPath(url: string, name: string): string

Parameters

url

string

Source URL string

name

string

String to be appended to URL

Returns

string

An updated URL string

base64decode(string)

Base64 decode.

function base64decode(encodedString: string): string

Parameters

encodedString

string

Returns

string

base64encode(string)

Base64 encode.

function base64encode(content: string): string

Parameters

content

string

Returns

string

delay(number, AbortSignalLike, Error)

Delay specified time interval.

function delay(timeInMs: number, aborter?: AbortSignalLike, abortError?: Error): Promise<unknown>

Parameters

timeInMs

number

aborter

AbortSignalLike

abortError

Error

Returns

Promise<unknown>

escapeURLPath(string)

Reserved URL characters must be properly escaped for Storage services like Blob or File.

URL encode and escape strategy for JSv10 SDKs

When customers pass a URL string into XXXURL classes constrcutor, the URL string may already be URL encoded or not. But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XXXURL constructors.

Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK.

This is what legacy V2 SDK does, simple and works for most of the cases.

  • When customer URL string is "http://account.blob.core.windows.net/con/b:", SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
  • When customer URL string is "http://account.blob.core.windows.net/con/b%3A", SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created.

But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two:

Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters.

This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped.

  • When customer URL string is "http://account.blob.core.windows.net/con/b:", SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created.
  • When customer URL string is "http://account.blob.core.windows.net/con/b%3A", There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created.
  • When customer URL string is "http://account.blob.core.windows.net/con/b%253A", There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created.

This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. If customer needs to create a blob with "%" in it's blob name, use "%25" insead of "%". Just like above 3rd sample. And following URL strings are invalid:

  • "http://account.blob.core.windows.net/con/b%"
  • "http://account.blob.core.windows.net/con/b%2"
  • "http://account.blob.core.windows.net/con/b%G"

Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string.

Strategy for containerName, blobName or other specific XXXName parameters in methods such as BlobURL.fromContainerURL(containerURL, blobName)

We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL.

See https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata

See https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata

function escapeURLPath(url: string): string

Parameters

url

string

Returns

string

generateBlockID(string, number)

Generate a 64 bytes base64 block ID string.

function generateBlockID(blockIDPrefix: string, blockIndex: number): string

Parameters

blockIDPrefix

string

blockIndex

number

Returns

string

getURLParameter(string, string)

Get URL parameter by name.

function getURLParameter(url: string, name: string): string | string[] | undefined

Parameters

url

string

name

string

Returns

string | string[] | undefined

getURLPath(string)

Get URL path from an URL string.

function getURLPath(url: string): string | undefined

Parameters

url

string

Source URL string

Returns

string | undefined

getURLPathAndQuery(string)

Get URL path and query from an URL string.

function getURLPathAndQuery(url: string): string | undefined

Parameters

url

string

Source URL string

Returns

string | undefined

getURLQueries(string)

Get URL query key value pairs from an URL string.

function getURLQueries(url: string): [key: string]: string

Parameters

url

string

Returns

[key: string]: string

getURLScheme(string)

Get URL scheme from an URL string.

function getURLScheme(url: string): string | undefined

Parameters

url

string

Source URL string

Returns

string | undefined

iEqual(string, string)

If two strings are equal when compared case insensitive.

function iEqual(str1: string, str2: string): boolean

Parameters

str1

string

str2

string

Returns

boolean

padStart(string, number, undefined | string)

String.prototype.padStart()

function padStart(currentString: string, targetLength: number, padString?: undefined | string): string

Parameters

currentString

string

targetLength

number

padString

undefined | string

Returns

string

setURLHost(string, string)

Set URL host.

function setURLHost(url: string, host: string): string

Parameters

url

string

Source URL string

host

string

New host string

Returns

string

An updated URL string

setURLParameter(string, string, undefined | string)

Set URL parameter name and value. If name exists in URL parameters, old value will be replaced by name key. If not provide value, the parameter will be deleted.

function setURLParameter(url: string, name: string, value?: undefined | string): string

Parameters

url

string

Source URL string

name

string

Parameter name

value

undefined | string

Returns

string

An updated URL string

truncatedISO8061Date(Date, undefined | false | true)

Rounds a date off to seconds.

function truncatedISO8061Date(date: Date, withMilliseconds?: undefined | false | true): string

Parameters

date

Date

withMilliseconds

undefined | false | true

Returns

string

Date string in ISO8061 format, with or without 7 milliseconds component

streamToBuffer(ReadableStream, Buffer, number, number, undefined | string)

Reads a readable stream into buffer. Fill the buffer from offset to end.

function streamToBuffer(stream: ReadableStream, buffer: Buffer, offset: number, end: number, encoding?: undefined | string): Promise<void>

Parameters

stream

ReadableStream

A Node.js Readable stream

buffer

Buffer

Buffer to be filled, length must >= offset

offset

number

From which position in the buffer to be filled, inclusive

end

number

To which position in the buffer to be filled, exclusive

encoding

undefined | string

Returns

Promise<void>

streamToBuffer2(ReadableStream, Buffer, undefined | string)

Reads a readable stream into buffer entirely.

function streamToBuffer2(stream: ReadableStream, buffer: Buffer, encoding?: undefined | string): Promise<number>

Parameters

stream

ReadableStream

A Node.js Readable stream

buffer

Buffer

Buffer to be filled, length must >= offset

encoding

undefined | string

Returns

Promise<number>

with the count of bytes read.