ShareDirectoryClient class

A ShareDirectoryClient represents a URL to the Azure Storage directory allowing you to manipulate its files and directories.

Extends

StorageClient

Constructors

ShareDirectoryClient(string, Credential_2 | TokenCredential, ShareClientOptions)

Creates an instance of DirectoryClient.

ShareDirectoryClient(string, Pipeline, ShareClientConfig)

Creates an instance of DirectoryClient.

Properties

name

The name of the directory

path

The full path of the directory

shareName

The share name corresponding to this directory client

Inherited Properties

accountName
url

URL string value.

Methods

create(DirectoryCreateOptions)

Creates a new directory under the specified share or parent directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-directory

createFile(string, number, FileCreateOptions)

Creates a new file or replaces a file under this directory. Note it only initializes the file with no content.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-file

createIfNotExists(DirectoryCreateOptions)

Creates a new directory under the specified share or parent directory if it does not already exists. If the directory already exists, it is not modified.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-directory

createSubdirectory(string, DirectoryCreateOptions)

Creates a new subdirectory under this directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-directory

delete(DirectoryDeleteOptions)

Removes the specified empty directory. Note that the directory must be empty before it can be deleted.

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-directory

deleteFile(string, FileDeleteOptions)

Removes the specified file under this directory from the storage account. When a file is successfully deleted, it is immediately removed from the storage account's index and is no longer accessible to clients. The file's data is later removed from the service during garbage collection.

Delete File will fail with status code 409 (Conflict) and error code SharingViolation if the file is open on an SMB client.

Delete File is not supported on a share snapshot, which is a read-only copy of a share. An attempt to perform this operation on a share snapshot will fail with 400 (InvalidQueryParameterValue)

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-file2

deleteIfExists(DirectoryDeleteOptions)

Removes the specified empty directory if it exists. Note that the directory must be empty before it can be deleted.

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-directory

deleteSubdirectory(string, DirectoryDeleteOptions)

Removes the specified empty sub directory under this directory. Note that the directory must be empty before it can be deleted.

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-directory

exists(DirectoryExistsOptions)

Returns true if the specified directory exists; false otherwise.

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

forceCloseAllHandles(DirectoryForceCloseHandlesSegmentOptions)

Force close all handles for a directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/force-close-handles

forceCloseHandle(string, DirectoryForceCloseHandlesOptions)

Force close a specific handle for a directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/force-close-handles

getDirectoryClient(string)

Creates a ShareDirectoryClient object for a sub directory.

getFileClient(string)

Creates a ShareFileClient object.

getProperties(DirectoryGetPropertiesOptions)

Returns all system properties for the specified directory, and can also be used to check the existence of a directory. The data returned does not include the files in the directory or any subdirectories.

See https://docs.microsoft.com/en-us/rest/api/storageservices/get-directory-properties

listFilesAndDirectories(DirectoryListFilesAndDirectoriesOptions)

Returns an async iterable iterator to list all the files and directories under the specified account.

.byPage() returns an async iterable iterator to list the files and directories in pages.

Example using for await syntax:

let i = 1;
for await (const entity of directoryClient.listFilesAndDirectories()) {
  if (entity.kind === "directory") {
    console.log(`${i++} - directory\t: ${entity.name}`);
  } else {
    console.log(`${i++} - file\t: ${entity.name}`);
  }
}

Example using iter.next():

let i = 1;
let iter = directoryClient.listFilesAndDirectories();
let entity = await iter.next();
while (!entity.done) {
  if (entity.value.kind === "directory") {
    console.log(`${i++} - directory\t: ${entity.value.name}`);
  } else {
    console.log(`${i++} - file\t: ${entity.value.name}`);
  }
  entity = await iter.next();
}

Example using byPage():

// passing optional maxPageSize in the page settings
let i = 1;
for await (const response of directoryClient
  .listFilesAndDirectories()
  .byPage({ maxPageSize: 20 })) {
  for (const fileItem of response.segment.fileItems) {
    console.log(`${i++} - file\t: ${fileItem.name}`);
  }
  for (const dirItem of response.segment.directoryItems) {
    console.log(`${i++} - directory\t: ${dirItem.name}`);
  }
}

Example using paging with a marker:

let i = 1;
let iterator = directoryClient.listFilesAndDirectories().byPage({ maxPageSize: 3 });
let response = (await iterator.next()).value;

// Prints 3 file and directory names
for (const fileItem of response.segment.fileItems) {
  console.log(`${i++} - file\t: ${fileItem.name}`);
}

for (const dirItem of response.segment.directoryItems) {
  console.log(`${i++} - directory\t: ${dirItem.name}`);
}

// Gets next marker
let dirMarker = response.continuationToken;

// Passing next marker as continuationToken
iterator = directoryClient
  .listFilesAndDirectories()
  .byPage({ continuationToken: dirMarker, maxPageSize: 4 });
response = (await iterator.next()).value;

// Prints 10 file and directory names
for (const fileItem of response.segment.fileItems) {
  console.log(`${i++} - file\t: ${fileItem.name}`);
}

for (const dirItem of response.segment.directoryItems) {
  console.log(`${i++} - directory\t: ${dirItem.name}`);
}
listHandles(DirectoryListHandlesOptions)

Returns an async iterable iterator to list all the handles. under the specified account.

.byPage() returns an async iterable iterator to list the handles in pages.

Example using for await syntax:

let i = 1;
let iter = dirClient.listHandles();
for await (const handle of iter) {
  console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
}

Example using iter.next():

let i = 1;
let iter = dirClient.listHandles();
let handleItem = await iter.next();
while (!handleItem.done) {
  console.log(`Handle ${i++}: ${handleItem.value.path}, opened time ${handleItem.value.openTime}, clientIp ${handleItem.value.clientIp}`);
  handleItem = await iter.next();
}

Example using byPage():

// passing optional maxPageSize in the page settings
let i = 1;
for await (const response of dirClient.listHandles({ recursive: true }).byPage({ maxPageSize: 20 })) {
  if (response.handleList) {
    for (const handle of response.handleList) {
      console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
    }
  }
}

Example using paging with a marker:

let i = 1;
let iterator = dirClient.listHandles().byPage({ maxPageSize: 2 });
let response = await iterator.next();

// Prints 2 handles
if (response.value.handleList) {
  for (const handle of response.value.handleList) {
    console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
  }
}

// Gets next marker
let marker = response.value.continuationToken;

// Passing next marker as continuationToken
console.log(`    continuation`);
iterator = dirClient.listHandles().byPage({ continuationToken: marker, maxPageSize: 10 });
response = await iterator.next();

// Prints 2 more handles assuming you have more than four directory/files opened
if (!response.done && response.value.handleList) {
  for (const handle of response.value.handleList) {
    console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
  }
}
rename(string, DirectoryRenameOptions)

Renames a directory. This API only supports renaming a directory in the same share.

setMetadata(Metadata, DirectorySetMetadataOptions)

Updates user defined metadata for the specified directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/set-directory-metadata

setProperties(DirectoryProperties)

Sets properties on the directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/set-directory-properties

Constructor Details

ShareDirectoryClient(string, Credential_2 | TokenCredential, ShareClientOptions)

Creates an instance of DirectoryClient.

new ShareDirectoryClient(url: string, credential?: Credential_2 | TokenCredential, options?: ShareClientOptions)

Parameters

url

string

A URL string pointing to Azure Storage file directory, such as "https://myaccount.file.core.windows.net/myshare/mydirectory". You can append a SAS if using AnonymousCredential, such as "https://myaccount.file.core.windows.net/myshare/mydirectory?sasString". This method accepts an encoded URL or non-encoded URL pointing to a directory. Encoded URL string will NOT be escaped twice, only special characters in URL path will be escaped. However, if a directory name includes %, directory name must be encoded in the URL. Such as a directory named "mydir%", the URL should be "https://myaccount.file.core.windows.net/myshare/mydir%25".

credential

Credential | TokenCredential

Such as AnonymousCredential or StorageSharedKeyCredential. If not specified, AnonymousCredential is used.

options
ShareClientOptions

Optional. Options to configure the HTTP pipeline.

ShareDirectoryClient(string, Pipeline, ShareClientConfig)

Creates an instance of DirectoryClient.

new ShareDirectoryClient(url: string, pipeline: Pipeline, options?: ShareClientConfig)

Parameters

url

string

A URL string pointing to Azure Storage file directory, such as "https://myaccount.file.core.windows.net/myshare/mydirectory". You can append a SAS if using AnonymousCredential, such as "https://myaccount.file.core.windows.net/myshare/mydirectory?sasString". This method accepts an encoded URL or non-encoded URL pointing to a directory. Encoded URL string will NOT be escaped twice, only special characters in URL path will be escaped. However, if a directory name includes %, directory name must be encoded in the URL. Such as a directory named "mydir%", the URL should be "https://myaccount.file.core.windows.net/myshare/mydir%25".

pipeline
Pipeline

Call newPipeline() to create a default pipeline, or provide a customized pipeline.

Property Details

name

The name of the directory

string name

Property Value

string

path

The full path of the directory

string path

Property Value

string

shareName

The share name corresponding to this directory client

string shareName

Property Value

string

Inherited Property Details

accountName

accountName: string

Property Value

string

Inherited From StorageClient.accountName

url

URL string value.

url: string

Property Value

string

Inherited From StorageClient.url

Method Details

create(DirectoryCreateOptions)

Creates a new directory under the specified share or parent directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-directory

function create(options?: DirectoryCreateOptions): Promise<DirectoryCreateResponse>

Parameters

options
DirectoryCreateOptions

Options to Directory Create operation.

Returns

Response data for the Directory operation.

createFile(string, number, FileCreateOptions)

Creates a new file or replaces a file under this directory. Note it only initializes the file with no content.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-file

function createFile(fileName: string, size: number, options?: FileCreateOptions): Promise<{ fileClient: ShareFileClient, fileCreateResponse: FileCreateResponse }>

Parameters

fileName

string

size

number

Specifies the maximum size in bytes for the file, up to 4 TB.

options
FileCreateOptions

Options to File Create operation.

Returns

Promise<{ fileClient: ShareFileClient, fileCreateResponse: FileCreateResponse }>

File creation response data and the corresponding file client.

createIfNotExists(DirectoryCreateOptions)

Creates a new directory under the specified share or parent directory if it does not already exists. If the directory already exists, it is not modified.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-directory

function createIfNotExists(options?: DirectoryCreateOptions): Promise<DirectoryCreateIfNotExistsResponse>

Parameters

Returns

createSubdirectory(string, DirectoryCreateOptions)

Creates a new subdirectory under this directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/create-directory

function createSubdirectory(directoryName: string, options?: DirectoryCreateOptions): Promise<{ directoryClient: ShareDirectoryClient, directoryCreateResponse: DirectoryCreateResponse }>

Parameters

directoryName

string

options
DirectoryCreateOptions

Options to Directory Create operation.

Returns

Promise<{ directoryClient: ShareDirectoryClient, directoryCreateResponse: DirectoryCreateResponse }>

Directory create response data and the corresponding DirectoryClient instance.

delete(DirectoryDeleteOptions)

Removes the specified empty directory. Note that the directory must be empty before it can be deleted.

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-directory

function delete(options?: DirectoryDeleteOptions): Promise<DirectoryDeleteResponse>

Parameters

options
DirectoryDeleteOptions

Options to Directory Delete operation.

Returns

Response data for the Directory Delete operation.

deleteFile(string, FileDeleteOptions)

Removes the specified file under this directory from the storage account. When a file is successfully deleted, it is immediately removed from the storage account's index and is no longer accessible to clients. The file's data is later removed from the service during garbage collection.

Delete File will fail with status code 409 (Conflict) and error code SharingViolation if the file is open on an SMB client.

Delete File is not supported on a share snapshot, which is a read-only copy of a share. An attempt to perform this operation on a share snapshot will fail with 400 (InvalidQueryParameterValue)

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-file2

function deleteFile(fileName: string, options?: FileDeleteOptions): Promise<FileDeleteResponse>

Parameters

fileName

string

Name of the file to delete

options
FileDeleteOptions

Options to File Delete operation.

Returns

File deletion response data.

deleteIfExists(DirectoryDeleteOptions)

Removes the specified empty directory if it exists. Note that the directory must be empty before it can be deleted.

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-directory

function deleteIfExists(options?: DirectoryDeleteOptions): Promise<DirectoryDeleteIfExistsResponse>

Parameters

Returns

deleteSubdirectory(string, DirectoryDeleteOptions)

Removes the specified empty sub directory under this directory. Note that the directory must be empty before it can be deleted.

See https://docs.microsoft.com/en-us/rest/api/storageservices/delete-directory

function deleteSubdirectory(directoryName: string, options?: DirectoryDeleteOptions): Promise<DirectoryDeleteResponse>

Parameters

directoryName

string

options
DirectoryDeleteOptions

Options to Directory Delete operation.

Returns

Directory deletion response data.

exists(DirectoryExistsOptions)

Returns true if the specified directory exists; false otherwise.

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

function exists(options?: DirectoryExistsOptions): Promise<boolean>

Parameters

options
DirectoryExistsOptions

options to Exists operation.

Returns

Promise<boolean>

forceCloseAllHandles(DirectoryForceCloseHandlesSegmentOptions)

Force close all handles for a directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/force-close-handles

function forceCloseAllHandles(options?: DirectoryForceCloseHandlesSegmentOptions): Promise<CloseHandlesInfo>

Parameters

Returns

Promise<CloseHandlesInfo>

forceCloseHandle(string, DirectoryForceCloseHandlesOptions)

Force close a specific handle for a directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/force-close-handles

function forceCloseHandle(handleId: string, options?: DirectoryForceCloseHandlesOptions): Promise<DirectoryForceCloseHandlesResponse>

Parameters

handleId

string

Specific handle ID, cannot be asterisk "*". Use forceCloseHandlesSegment() to close all handles.

Returns

getDirectoryClient(string)

Creates a ShareDirectoryClient object for a sub directory.

function getDirectoryClient(subDirectoryName: string): ShareDirectoryClient

Parameters

subDirectoryName

string

A subdirectory name

Returns

The ShareDirectoryClient object for the given subdirectory name.

Example usage:

const directoryClient = shareClient.getDirectoryClient("<directory name>");
await directoryClient.create();
console.log("Created directory successfully");

getFileClient(string)

Creates a ShareFileClient object.

function getFileClient(fileName: string): ShareFileClient

Parameters

fileName

string

A file name.

Returns

A new ShareFileClient object for the given file name.

Example usage:

const content = "Hello world!"

const fileClient = directoryClient.getFileClient("<file name>");

await fileClient.create(content.length);
console.log("Created file successfully!");

await fileClient.uploadRange(content, 0, content.length);
console.log("Updated file successfully!")

getProperties(DirectoryGetPropertiesOptions)

Returns all system properties for the specified directory, and can also be used to check the existence of a directory. The data returned does not include the files in the directory or any subdirectories.

See https://docs.microsoft.com/en-us/rest/api/storageservices/get-directory-properties

function getProperties(options?: DirectoryGetPropertiesOptions): Promise<DirectoryGetPropertiesResponse>

Parameters

options
DirectoryGetPropertiesOptions

Options to Directory Get Properties operation.

Returns

Response data for the Directory Get Properties operation.

listFilesAndDirectories(DirectoryListFilesAndDirectoriesOptions)

Returns an async iterable iterator to list all the files and directories under the specified account.

.byPage() returns an async iterable iterator to list the files and directories in pages.

Example using for await syntax:

let i = 1;
for await (const entity of directoryClient.listFilesAndDirectories()) {
  if (entity.kind === "directory") {
    console.log(`${i++} - directory\t: ${entity.name}`);
  } else {
    console.log(`${i++} - file\t: ${entity.name}`);
  }
}

Example using iter.next():

let i = 1;
let iter = directoryClient.listFilesAndDirectories();
let entity = await iter.next();
while (!entity.done) {
  if (entity.value.kind === "directory") {
    console.log(`${i++} - directory\t: ${entity.value.name}`);
  } else {
    console.log(`${i++} - file\t: ${entity.value.name}`);
  }
  entity = await iter.next();
}

Example using byPage():

// passing optional maxPageSize in the page settings
let i = 1;
for await (const response of directoryClient
  .listFilesAndDirectories()
  .byPage({ maxPageSize: 20 })) {
  for (const fileItem of response.segment.fileItems) {
    console.log(`${i++} - file\t: ${fileItem.name}`);
  }
  for (const dirItem of response.segment.directoryItems) {
    console.log(`${i++} - directory\t: ${dirItem.name}`);
  }
}

Example using paging with a marker:

let i = 1;
let iterator = directoryClient.listFilesAndDirectories().byPage({ maxPageSize: 3 });
let response = (await iterator.next()).value;

// Prints 3 file and directory names
for (const fileItem of response.segment.fileItems) {
  console.log(`${i++} - file\t: ${fileItem.name}`);
}

for (const dirItem of response.segment.directoryItems) {
  console.log(`${i++} - directory\t: ${dirItem.name}`);
}

// Gets next marker
let dirMarker = response.continuationToken;

// Passing next marker as continuationToken
iterator = directoryClient
  .listFilesAndDirectories()
  .byPage({ continuationToken: dirMarker, maxPageSize: 4 });
response = (await iterator.next()).value;

// Prints 10 file and directory names
for (const fileItem of response.segment.fileItems) {
  console.log(`${i++} - file\t: ${fileItem.name}`);
}

for (const dirItem of response.segment.directoryItems) {
  console.log(`${i++} - directory\t: ${dirItem.name}`);
}
function listFilesAndDirectories(options?: DirectoryListFilesAndDirectoriesOptions): PagedAsyncIterableIterator<({ kind: "file" } & FileItem) | ({ kind: "directory" } & DirectoryItem), DirectoryListFilesAndDirectoriesSegmentResponse, PageSettings>

Parameters

options
DirectoryListFilesAndDirectoriesOptions

Options to list files and directories operation.

Returns

An asyncIterableIterator that supports paging.

listHandles(DirectoryListHandlesOptions)

Returns an async iterable iterator to list all the handles. under the specified account.

.byPage() returns an async iterable iterator to list the handles in pages.

Example using for await syntax:

let i = 1;
let iter = dirClient.listHandles();
for await (const handle of iter) {
  console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
}

Example using iter.next():

let i = 1;
let iter = dirClient.listHandles();
let handleItem = await iter.next();
while (!handleItem.done) {
  console.log(`Handle ${i++}: ${handleItem.value.path}, opened time ${handleItem.value.openTime}, clientIp ${handleItem.value.clientIp}`);
  handleItem = await iter.next();
}

Example using byPage():

// passing optional maxPageSize in the page settings
let i = 1;
for await (const response of dirClient.listHandles({ recursive: true }).byPage({ maxPageSize: 20 })) {
  if (response.handleList) {
    for (const handle of response.handleList) {
      console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
    }
  }
}

Example using paging with a marker:

let i = 1;
let iterator = dirClient.listHandles().byPage({ maxPageSize: 2 });
let response = await iterator.next();

// Prints 2 handles
if (response.value.handleList) {
  for (const handle of response.value.handleList) {
    console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
  }
}

// Gets next marker
let marker = response.value.continuationToken;

// Passing next marker as continuationToken
console.log(`    continuation`);
iterator = dirClient.listHandles().byPage({ continuationToken: marker, maxPageSize: 10 });
response = await iterator.next();

// Prints 2 more handles assuming you have more than four directory/files opened
if (!response.done && response.value.handleList) {
  for (const handle of response.value.handleList) {
    console.log(`Handle ${i++}: ${handle.path}, opened time ${handle.openTime}, clientIp ${handle.clientIp}`);
  }
}
function listHandles(options?: DirectoryListHandlesOptions): PagedAsyncIterableIterator<HandleItem, DirectoryListHandlesResponse, PageSettings>

Parameters

options
DirectoryListHandlesOptions

Options to list handles operation.

An asyncIterableIterator that supports paging.

Returns

rename(string, DirectoryRenameOptions)

Renames a directory. This API only supports renaming a directory in the same share.

function rename(destinationPath: string, options?: DirectoryRenameOptions): Promise<{ destinationDirectoryClient: ShareDirectoryClient, directoryRenameResponse: DirectoryRenameResponse }>

Parameters

destinationPath

string

Specifies the destination path to rename to. The path will be encoded to put into a URL to specify the destination.

options
DirectoryRenameOptions

Options for the renaming operation.

Returns

Promise<{ destinationDirectoryClient: ShareDirectoryClient, directoryRenameResponse: DirectoryRenameResponse }>

Response data for the file renaming operation.

Example usage:


// Rename the directory
await diretoryClient.rename(destinationPath);
console.log("Renamed directory successfully!");

setMetadata(Metadata, DirectorySetMetadataOptions)

Updates user defined metadata for the specified directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/set-directory-metadata

function setMetadata(metadata?: Metadata, options?: DirectorySetMetadataOptions): Promise<DirectorySetMetadataResponse>

Parameters

metadata
Metadata

If no metadata provided, all existing directory metadata will be removed

options
DirectorySetMetadataOptions

Options to Directory Set Metadata operation.

Returns

Response data for the Directory Set Metadata operation.

setProperties(DirectoryProperties)

Sets properties on the directory.

See https://docs.microsoft.com/en-us/rest/api/storageservices/set-directory-properties

function setProperties(properties?: DirectoryProperties): Promise<DirectorySetPropertiesResponse>

Parameters

properties
DirectoryProperties

Returns