Поделиться через


ShareDirectoryClient class

ShareDirectoryClient представляет URL-адрес каталога службы хранилища Azure, позволяющий управлять файлами и каталогами.

Extends

StorageClient

Конструкторы

ShareDirectoryClient(string, Credential | TokenCredential, ShareClientOptions)

Создает экземпляр DirectoryClient.

ShareDirectoryClient(string, Pipeline, ShareClientConfig)

Создает экземпляр DirectoryClient.

Свойства

name

Имя каталога

path

Полный путь к каталогу

shareName

Имя общей папки, соответствующее этому клиенту каталога

Унаследованные свойства

accountName
url

Значение строки URL-адреса.

Методы

create(DirectoryCreateOptions)

Создает новый каталог под указанным общим ресурсом или родительским каталогом.

См. https://learn.microsoft.com/rest/api/storageservices/create-directory

createFile(string, number, FileCreateOptions)

Создает новый файл или заменяет файл в этом каталоге. Обратите внимание, что файл инициализируется только без содержимого.

См. https://learn.microsoft.com/rest/api/storageservices/create-file

createIfNotExists(DirectoryCreateOptions)

Создает новый каталог под указанным общим ресурсом или родительским каталогом, если он еще не существует. Если каталог уже существует, он не изменяется.

См. https://learn.microsoft.com/rest/api/storageservices/create-directory

createSubdirectory(string, DirectoryCreateOptions)

Создает подкаталог в этом каталоге.

См. https://learn.microsoft.com/rest/api/storageservices/create-directory

delete(DirectoryDeleteOptions)

Удаляет указанный пустой каталог. Обратите внимание, что каталог должен быть пустым, прежде чем его можно удалить.

См. https://learn.microsoft.com/rest/api/storageservices/delete-directory

deleteFile(string, FileDeleteOptions)

Удаляет указанный файл в этом каталоге из учетной записи хранения. При успешном удалении файла он немедленно удаляется из индекса учетной записи хранения и больше недоступен клиентам. Данные файла позже удаляются из службы во время сборки мусора.

Удаление файла завершится ошибкой с кодом состояния 409 (конфликт) и кодом ошибки ShareViolation, если файл открыт на клиенте SMB.

Удаление файла не поддерживается в моментальном снимке общего ресурса, который является копией общего ресурса только для чтения. Попытка выполнить эту операцию на моментальном снимке общего ресурса завершится ошибкой 400 (InvalidQueryParameterValue)

См. https://learn.microsoft.com/rest/api/storageservices/delete-file2

deleteIfExists(DirectoryDeleteOptions)

Удаляет указанный пустой каталог, если он существует. Обратите внимание, что каталог должен быть пустым, прежде чем его можно удалить.

См. https://learn.microsoft.com/rest/api/storageservices/delete-directory

deleteSubdirectory(string, DirectoryDeleteOptions)

Удаляет указанный пустой вложенный каталог в этом каталоге. Обратите внимание, что каталог должен быть пустым, прежде чем его можно удалить.

См. https://learn.microsoft.com/rest/api/storageservices/delete-directory

exists(DirectoryExistsOptions)

Возвращает значение true, если указанный каталог существует; False в противном случае.

ПРИМЕЧАНИЕ. Используйте эту функцию с осторожностью, так как существующий каталог может быть удален другими клиентами или приложениями. Наоборот, новые каталоги могут быть добавлены другими клиентами или приложениями после завершения этой функции.

forceCloseAllHandles(DirectoryForceCloseHandlesSegmentOptions)

Принудительно закройте все дескрипторы для каталога.

См. https://learn.microsoft.com/rest/api/storageservices/force-close-handles

forceCloseHandle(string, DirectoryForceCloseHandlesOptions)

Принудительно закройте определенный дескриптор для каталога.

См. https://learn.microsoft.com/rest/api/storageservices/force-close-handles

getDirectoryClient(string)

Создает объект ShareDirectoryClient для подкаталога.

getFileClient(string)

Создает объект ShareFileClient.

getProperties(DirectoryGetPropertiesOptions)

Возвращает все системные свойства для указанного каталога, а также можно использовать для проверки существования каталога. Возвращенные данные не содержат файлы в каталоге или в подкаталогах.

См. https://learn.microsoft.com/rest/api/storageservices/get-directory-properties

listFilesAndDirectories(DirectoryListFilesAndDirectoriesOptions)

Возвращает асинхронный итератор для перечисления всех файлов и каталогов в указанной учетной записи.

.byPage() возвращает асинхронный итератор для перечисления файлов и каталогов на страницах.

Пример использования синтаксиса for await:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

Пример использования iter.next():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

Пример использования byPage():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let i = 1;
for await (const response of directoryClient
  .listFilesAndDirectories()
  .byPage({ maxPageSize: 20 })) {
  console.log(`Page ${i++}:`);
  for (const item of response.segment.directoryItems) {
    console.log(`\tdirectory: ${item.name}`);
  }
  for (const item of response.segment.fileItems) {
    console.log(`\tfile: ${item.name}`);
  }
}

Пример использования разбиения по страницам с маркером:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

for await (const item of response.segment.directoryItems) {
  console.log(`\tdirectory: ${item.name}`);
}

for await (const item of response.segment.fileItems) {
  console.log(`\tfile: ${item.name}`);
}

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

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

for await (const item of response.segment.directoryItems) {
  console.log(`\tdirectory: ${item.name}`);
}

for await (const item of response.segment.fileItems) {
  console.log(`\tfile: ${item.name}`);
}
listHandles(DirectoryListHandlesOptions)

Возвращает асинхронный итератор для перечисления всех дескрипторов. под указанной учетной записью.

.byPage() возвращает асинхронный итератор для перечисления дескрипторов на страницах.

Пример использования синтаксиса for await:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

for await (const handle of directoryClient.listHandles()) {
  console.log(`Handle: ${handle.handleId}`);
}

Пример использования iter.next():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

const handleIter = directoryClient.listHandles();
let { value, done } = await handleIter.next();
while (!done) {
  console.log(`Handle: ${value.handleId}`);
  ({ value, done } = await handleIter.next());
}

Пример использования byPage():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let i = 1;
for await (const response of directoryClient.listHandles().byPage({ maxPageSize: 20 })) {
  console.log(`Page ${i++}:`);
  for (const handle of response.handleList || []) {
    console.log(`\thandle: ${handle.handleId}`);
  }
}

Пример использования разбиения по страницам с маркером:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let iterator = directoryClient.listHandles().byPage({ maxPageSize: 2 });
let response = (await iterator.next()).value;

for await (const handle of response.handleList || []) {
  console.log(`\thandle: ${handle.handleId}`);
}

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

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

for await (const handle of response.handleList || []) {
  console.log(`\thandle: ${handle.handleId}`);
}
rename(string, DirectoryRenameOptions)

Переименовывает каталог. Этот API поддерживает переименование каталога в той же общей папке.

setMetadata(Metadata, DirectorySetMetadataOptions)

Обновляет пользовательские метаданные для указанного каталога.

См. https://learn.microsoft.com/rest/api/storageservices/set-directory-metadata

setProperties(DirectoryProperties)

Задает свойства в каталоге.

См. https://learn.microsoft.com/rest/api/storageservices/set-directory-properties

Сведения о конструкторе

ShareDirectoryClient(string, Credential | TokenCredential, ShareClientOptions)

Создает экземпляр DirectoryClient.

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

Параметры

url

string

Строка URL-адреса, указывающая на каталог файлов службы хранилища Azure, например "https://myaccount.file.core.windows.net/myshare/mydirectory". При использовании AnonymousCredential можно добавить SAS, например "https://myaccount.file.core.windows.net/myshare/mydirectory?sasString". Этот метод принимает закодированный URL-адрес или некодированный URL-адрес, указывающий на каталог. Строка ЗАкодированного URL-адреса не будет экранирована дважды, будут экранированы только специальные символы в пути URL-адреса. Однако если имя каталога содержит %, имя каталога должно быть закодировано в URL-адресе. Например, каталог с именем "mydir%", URL-адрес должен быть "https://myaccount.file.core.windows.net/myshare/mydir%25".

credential

Credential | TokenCredential

Например, AnonymousCredential или StorageSharedKeyCredential. Если не указано, используется AnonymousCredential.

options
ShareClientOptions

Optional. Параметры настройки конвейера HTTP.

ShareDirectoryClient(string, Pipeline, ShareClientConfig)

Создает экземпляр DirectoryClient.

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

Параметры

url

string

Строка URL-адреса, указывающая на каталог файлов службы хранилища Azure, например "https://myaccount.file.core.windows.net/myshare/mydirectory". При использовании AnonymousCredential можно добавить SAS, например "https://myaccount.file.core.windows.net/myshare/mydirectory?sasString". Этот метод принимает закодированный URL-адрес или некодированный URL-адрес, указывающий на каталог. Строка ЗАкодированного URL-адреса не будет экранирована дважды, будут экранированы только специальные символы в пути URL-адреса. Однако если имя каталога содержит %, имя каталога должно быть закодировано в URL-адресе. Например, каталог с именем "mydir%", URL-адрес должен быть "https://myaccount.file.core.windows.net/myshare/mydir%25".

pipeline
Pipeline

Вызовите newPipeline() для создания конвейера по умолчанию или предоставления настраиваемого конвейера.

Сведения о свойстве

name

Имя каталога

string name

Значение свойства

string

path

Полный путь к каталогу

string path

Значение свойства

string

shareName

Имя общей папки, соответствующее этому клиенту каталога

string shareName

Значение свойства

string

Сведения об унаследованном свойстве

accountName

accountName: string

Значение свойства

string

наследуется от storageClient.accountName

url

Значение строки URL-адреса.

url: string

Значение свойства

string

наследуется от StorageClient.url

Сведения о методе

create(DirectoryCreateOptions)

Создает новый каталог под указанным общим ресурсом или родительским каталогом.

См. https://learn.microsoft.com/rest/api/storageservices/create-directory

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

Параметры

options
DirectoryCreateOptions

Параметры операции создания каталога.

Возвращаемое значение

Ответные данные для операции каталога.

createFile(string, number, FileCreateOptions)

Создает новый файл или заменяет файл в этом каталоге. Обратите внимание, что файл инициализируется только без содержимого.

См. https://learn.microsoft.com/rest/api/storageservices/create-file

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

Параметры

fileName

string

size

number

Задает максимальный размер в байтах для файла до 4 ТБ.

options
FileCreateOptions

Параметры операции создания файла.

Возвращаемое значение

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

Данные ответа на создание файла и соответствующий клиент файла.

createIfNotExists(DirectoryCreateOptions)

Создает новый каталог под указанным общим ресурсом или родительским каталогом, если он еще не существует. Если каталог уже существует, он не изменяется.

См. https://learn.microsoft.com/rest/api/storageservices/create-directory

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

Параметры

Возвращаемое значение

createSubdirectory(string, DirectoryCreateOptions)

Создает подкаталог в этом каталоге.

См. https://learn.microsoft.com/rest/api/storageservices/create-directory

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

Параметры

directoryName

string

options
DirectoryCreateOptions

Параметры операции создания каталога.

Возвращаемое значение

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

Каталог создает данные ответа и соответствующий экземпляр DirectoryClient.

delete(DirectoryDeleteOptions)

Удаляет указанный пустой каталог. Обратите внимание, что каталог должен быть пустым, прежде чем его можно удалить.

См. https://learn.microsoft.com/rest/api/storageservices/delete-directory

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

Параметры

options
DirectoryDeleteOptions

Параметры операции удаления каталога.

Возвращаемое значение

Ответные данные для операции удаления каталога.

deleteFile(string, FileDeleteOptions)

Удаляет указанный файл в этом каталоге из учетной записи хранения. При успешном удалении файла он немедленно удаляется из индекса учетной записи хранения и больше недоступен клиентам. Данные файла позже удаляются из службы во время сборки мусора.

Удаление файла завершится ошибкой с кодом состояния 409 (конфликт) и кодом ошибки ShareViolation, если файл открыт на клиенте SMB.

Удаление файла не поддерживается в моментальном снимке общего ресурса, который является копией общего ресурса только для чтения. Попытка выполнить эту операцию на моментальном снимке общего ресурса завершится ошибкой 400 (InvalidQueryParameterValue)

См. https://learn.microsoft.com/rest/api/storageservices/delete-file2

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

Параметры

fileName

string

Имя файла для удаления

options
FileDeleteOptions

Параметры операции удаления файлов.

Возвращаемое значение

Данные ответа на удаление файлов.

deleteIfExists(DirectoryDeleteOptions)

Удаляет указанный пустой каталог, если он существует. Обратите внимание, что каталог должен быть пустым, прежде чем его можно удалить.

См. https://learn.microsoft.com/rest/api/storageservices/delete-directory

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

Параметры

Возвращаемое значение

deleteSubdirectory(string, DirectoryDeleteOptions)

Удаляет указанный пустой вложенный каталог в этом каталоге. Обратите внимание, что каталог должен быть пустым, прежде чем его можно удалить.

См. https://learn.microsoft.com/rest/api/storageservices/delete-directory

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

Параметры

directoryName

string

options
DirectoryDeleteOptions

Параметры операции удаления каталога.

Возвращаемое значение

Данные ответа на удаление каталога.

exists(DirectoryExistsOptions)

Возвращает значение true, если указанный каталог существует; False в противном случае.

ПРИМЕЧАНИЕ. Используйте эту функцию с осторожностью, так как существующий каталог может быть удален другими клиентами или приложениями. Наоборот, новые каталоги могут быть добавлены другими клиентами или приложениями после завершения этой функции.

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

Параметры

options
DirectoryExistsOptions

параметры операции "Существует".

Возвращаемое значение

Promise<boolean>

forceCloseAllHandles(DirectoryForceCloseHandlesSegmentOptions)

Принудительно закройте все дескрипторы для каталога.

См. https://learn.microsoft.com/rest/api/storageservices/force-close-handles

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

Параметры

Возвращаемое значение

Promise<CloseHandlesInfo>

forceCloseHandle(string, DirectoryForceCloseHandlesOptions)

Принудительно закройте определенный дескриптор для каталога.

См. https://learn.microsoft.com/rest/api/storageservices/force-close-handles

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

Параметры

handleId

string

Идентификатор определенного дескриптора не может быть звездочкой "*". Используйте forceCloseHandlesSegment() для закрытия всех дескрипторов.

Возвращаемое значение

getDirectoryClient(string)

Создает объект ShareDirectoryClient для подкаталога.

function getDirectoryClient(subDirectoryName: string): ShareDirectoryClient

Параметры

subDirectoryName

string

Имя подкаталога

Возвращаемое значение

Объект ShareDirectoryClient для заданного имени подкаталога.

Пример использования:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const shareClient = serviceClient.getShareClient(shareName);
const directoryClient = shareClient.getDirectoryClient(directoryName);
await directoryClient.create();

getFileClient(string)

Создает объект ShareFileClient.

function getFileClient(fileName: string): ShareFileClient

Параметры

fileName

string

Имя файла.

Возвращаемое значение

Новый объект ShareFileClient для заданного имени файла.

Пример использования:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

const content = "Hello World!";
const fileName = `newdirectory${+new Date()}`;
const fileClient = directoryClient.getFileClient(fileName);
await fileClient.create(content.length);
console.log(`Create file ${fileName} successfully`);

// Upload file range
await fileClient.uploadRange(content, 0, content.length);
console.log(`Upload file range "${content}" to ${fileName} successfully`);

getProperties(DirectoryGetPropertiesOptions)

Возвращает все системные свойства для указанного каталога, а также можно использовать для проверки существования каталога. Возвращенные данные не содержат файлы в каталоге или в подкаталогах.

См. https://learn.microsoft.com/rest/api/storageservices/get-directory-properties

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

Параметры

options
DirectoryGetPropertiesOptions

Параметры операции получения свойств каталога.

Возвращаемое значение

Ответные данные для операции получения свойств каталога.

listFilesAndDirectories(DirectoryListFilesAndDirectoriesOptions)

Возвращает асинхронный итератор для перечисления всех файлов и каталогов в указанной учетной записи.

.byPage() возвращает асинхронный итератор для перечисления файлов и каталогов на страницах.

Пример использования синтаксиса for await:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

Пример использования iter.next():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

Пример использования byPage():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let i = 1;
for await (const response of directoryClient
  .listFilesAndDirectories()
  .byPage({ maxPageSize: 20 })) {
  console.log(`Page ${i++}:`);
  for (const item of response.segment.directoryItems) {
    console.log(`\tdirectory: ${item.name}`);
  }
  for (const item of response.segment.fileItems) {
    console.log(`\tfile: ${item.name}`);
  }
}

Пример использования разбиения по страницам с маркером:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

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

for await (const item of response.segment.directoryItems) {
  console.log(`\tdirectory: ${item.name}`);
}

for await (const item of response.segment.fileItems) {
  console.log(`\tfile: ${item.name}`);
}

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

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

for await (const item of response.segment.directoryItems) {
  console.log(`\tdirectory: ${item.name}`);
}

for await (const item of response.segment.fileItems) {
  console.log(`\tfile: ${item.name}`);
}
function listFilesAndDirectories(options?: DirectoryListFilesAndDirectoriesOptions): PagedAsyncIterableIterator<({ kind: "file" } & FileItem) | ({ kind: "directory" } & DirectoryItem), DirectoryListFilesAndDirectoriesSegmentResponse, PageSettings>

Параметры

options
DirectoryListFilesAndDirectoriesOptions

Параметры для перечисления файлов и каталогов.

Возвращаемое значение

AsyncIterableIterator, поддерживающий разбиение по страницам.

listHandles(DirectoryListHandlesOptions)

Возвращает асинхронный итератор для перечисления всех дескрипторов. под указанной учетной записью.

.byPage() возвращает асинхронный итератор для перечисления дескрипторов на страницах.

Пример использования синтаксиса for await:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

for await (const handle of directoryClient.listHandles()) {
  console.log(`Handle: ${handle.handleId}`);
}

Пример использования iter.next():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

const handleIter = directoryClient.listHandles();
let { value, done } = await handleIter.next();
while (!done) {
  console.log(`Handle: ${value.handleId}`);
  ({ value, done } = await handleIter.next());
}

Пример использования byPage():

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let i = 1;
for await (const response of directoryClient.listHandles().byPage({ maxPageSize: 20 })) {
  console.log(`Page ${i++}:`);
  for (const handle of response.handleList || []) {
    console.log(`\thandle: ${handle.handleId}`);
  }
}

Пример использования разбиения по страницам с маркером:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

let iterator = directoryClient.listHandles().byPage({ maxPageSize: 2 });
let response = (await iterator.next()).value;

for await (const handle of response.handleList || []) {
  console.log(`\thandle: ${handle.handleId}`);
}

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

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

for await (const handle of response.handleList || []) {
  console.log(`\thandle: ${handle.handleId}`);
}
function listHandles(options?: DirectoryListHandlesOptions): PagedAsyncIterableIterator<HandleItem, DirectoryListHandlesResponse, PageSettings>

Параметры

options
DirectoryListHandlesOptions

Параметры для перечисления операций обработки.

AsyncIterableIterator, поддерживающий разбиение по страницам.

Возвращаемое значение

rename(string, DirectoryRenameOptions)

Переименовывает каталог. Этот API поддерживает переименование каталога в той же общей папке.

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

Параметры

destinationPath

string

Указывает путь назначения для переименования. Путь будет закодирован для вставки в URL-адрес, чтобы указать назначение.

options
DirectoryRenameOptions

Параметры для операции переименования.

Возвращаемое значение

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

Ответные данные для операции переименования файла.

Пример использования:

import { StorageSharedKeyCredential, ShareServiceClient } from "@azure/storage-file-share";

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new StorageSharedKeyCredential(account, accountKey);
const serviceClient = new ShareServiceClient(
  `https://${account}.file.core.windows.net`,
  credential,
);

const shareName = "<share name>";
const directoryName = "<directory name>";
const destinationPath = "<destination path>";
const directoryClient = serviceClient.getShareClient(shareName).getDirectoryClient(directoryName);

await directoryClient.rename(destinationPath);

setMetadata(Metadata, DirectorySetMetadataOptions)

Обновляет пользовательские метаданные для указанного каталога.

См. https://learn.microsoft.com/rest/api/storageservices/set-directory-metadata

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

Параметры

metadata
Metadata

Если метаданные отсутствуют, все существующие метаданные каталога будут удалены.

options
DirectorySetMetadataOptions

Параметры операции задания метаданных для каталога.

Возвращаемое значение

Ответные данные для операции метаданных набора каталогов.

setProperties(DirectoryProperties)

Задает свойства в каталоге.

См. https://learn.microsoft.com/rest/api/storageservices/set-directory-properties

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

Параметры

properties
DirectoryProperties

Возвращаемое значение