Compartilhar via


DataLakeServiceClient class

O DataLakeServiceClient permite manipular recursos de serviço e sistemas de arquivos do Azure Data Lake. A conta de armazenamento fornece o namespace de nível superior para o serviço Data Lake.

Extends

StorageClient

Construtores

DataLakeServiceClient(string, Pipeline)

Cria uma instância de DataLakeServiceClient da URL e do pipeline.

DataLakeServiceClient(string, StorageSharedKeyCredential | AnonymousCredential | TokenCredential, StoragePipelineOptions)

Cria uma instância de DataLakeServiceClient da URL.

Propriedades herdadas

accountName
credential

Como AnonymousCredential, StorageSharedKeyCredential ou qualquer credencial do pacote @azure/identity para autenticar solicitações para o serviço. Você também pode fornecer um objeto que implementa a interface TokenCredential. Se não for especificado, AnonymousCredential será usado.

url

Valor da cadeia de caracteres de URL codificada.

Métodos

fromConnectionString(string, StoragePipelineOptions)

Cria uma instância de DataLakeServiceClient da cadeia de conexão.

generateAccountSasUrl(Date, AccountSASPermissions, string, ServiceGenerateAccountSasUrlOptions)

Disponível somente para DataLakeServiceClient construído com uma credencial de chave compartilhada.

Gera um URI de SAS (Assinatura de Acesso Compartilhado) de conta com base nas propriedades e parâmetros do cliente passados. A SAS é assinada pela credencial de chave compartilhada do cliente.

Consulte https://learn.microsoft.com/rest/api/storageservices/create-account-sas

generateSasStringToSign(Date, AccountSASPermissions, string, ServiceGenerateAccountSasUrlOptions)

Disponível somente para DataLakeServiceClient construído com uma credencial de chave compartilhada.

Gera uma cadeia de caracteres para assinar uma SAS (Assinatura de Acesso Compartilhado) de conta com base nas propriedades e parâmetros do cliente passados. A SAS é assinada pela credencial de chave compartilhada do cliente.

Consulte https://learn.microsoft.com/rest/api/storageservices/create-account-sas

getFileSystemClient(string)

Cria um objeto DataLakeFileSystemClient.

getProperties(ServiceGetPropertiesOptions)

Obtém as propriedades do ponto de extremidade do serviço Blob de uma conta de armazenamento, incluindo propriedades para as regras de Análise de Armazenamento e CORS (Compartilhamento de Recursos entre Origens).

Consulte https://learn.microsoft.com/rest/api/storageservices/get-blob-service-properties

getUserDelegationKey(Date, Date, ServiceGetUserDelegationKeyOptions)

DISPONÍVEL SOMENTE AO USAR A AUTENTICAÇÃO DE TOKEN DE PORTADOR (TokenCredential).

Recupera uma chave de delegação do usuário para o serviço Data Lake. Essa é apenas uma operação válida ao usar a autenticação de token de portador.

Example

import {
  DataLakeServiceClient,
  generateDataLakeSASQueryParameters,
  FileSystemSASPermissions,
  SASProtocol,
} from "@azure/storage-file-datalake";

const account = "<account>";
const sas = "<sas token>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net${sas}`,
);

const fileSystemName = "<file system name>";
const accountName = "<account name>";
const startsOn = new Date();
const expiresOn = new Date(+new Date() + 86400 * 1000);
// Generate user delegation SAS for a file system
const userDelegationKey = await datalakeServiceClient.getUserDelegationKey(startsOn, expiresOn);
const fileSystemSAS = generateDataLakeSASQueryParameters(
  {
    fileSystemName, // Required
    permissions: FileSystemSASPermissions.parse("racwdl"), // Required
    startsOn, // Required. Date type
    expiresOn, // Optional. Date type
    ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional
    protocol: SASProtocol.HttpsAndHttp, // Optional
    version: "2018-11-09", // Must greater than or equal to 2018-11-09 to generate user delegation SAS
  },
  userDelegationKey, // UserDelegationKey
  accountName,
).toString();

Consulte https://learn.microsoft.com/rest/api/storageservices/get-user-delegation-key

listFileSystems(ServiceListFileSystemsOptions)

Retorna um iterador iterável assíncrono para listar todos os sistemas de arquivos na conta especificada.

.byPage() retorna um iterador iterável assíncrono para listar os sistemas de arquivos em páginas.

Exemplo usando for await sintaxe:

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
const fileSystems = datalakeServiceClient.listFileSystems();
for await (const fileSystem of fileSystems) {
  console.log(`File system ${i++}: ${fileSystem.name}`);
}

Exemplo usando iter.next():

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
const fileSystems = datalakeServiceClient.listFileSystems();
let { value, done } = await fileSystems.next();
while (!done) {
  console.log(`File system ${i++}: ${value.name}`);
  ({ value, done } = await fileSystems.next());
}

Exemplo usando byPage():

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
for await (const response of datalakeServiceClient.listFileSystems().byPage({ maxPageSize: 20 })) {
  if (response.fileSystemItems) {
    for (const fileSystem of response.fileSystemItems) {
      console.log(`File System ${i++}: ${fileSystem.name}`);
    }
  }
}

Exemplo usando a paginação com um marcador:

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
let fileSystems = datalakeServiceClient.listFileSystems().byPage({ maxPageSize: 2 });
let response = (await fileSystems.next()).value;
// Prints 2 file systems
if (response.fileSystemItems) {
  for (const fileSystem of response.fileSystemItems) {
    console.log(`File system ${i++}: ${fileSystem.name}`);
  }
}
// Gets next marker
let marker = response.continuationToken;
// Passing next marker as continuationToken
fileSystems = datalakeServiceClient
  .listFileSystems()
  .byPage({ continuationToken: marker, maxPageSize: 10 });
response = (await fileSystems.next()).value;
// Prints 10 file systems
if (response.fileSystemItems) {
  for (const fileSystem of response.fileSystemItems) {
    console.log(`File system ${i++}: ${fileSystem.name}`);
  }
}

Consulte https://learn.microsoft.com/rest/api/storageservices/list-containers2

setProperties(BlobServiceProperties, ServiceSetPropertiesOptions)

Define propriedades para o ponto de extremidade do serviço Blob de uma conta de armazenamento, incluindo propriedades para análise de armazenamento, regras cors (compartilhamento de recursos entre origens) e configurações de exclusão reversível.

Consulte https://learn.microsoft.com/rest/api/storageservices/set-blob-service-properties

undeleteFileSystem(string, string, ServiceUndeleteFileSystemOptions)

Restaurar um sistema de arquivos excluído anteriormente. Essa API só estará funcional se a Exclusão Reversível do Contêiner estiver habilitada para a conta de armazenamento.

Detalhes do construtor

DataLakeServiceClient(string, Pipeline)

Cria uma instância de DataLakeServiceClient da URL e do pipeline.

new DataLakeServiceClient(url: string, pipeline: Pipeline)

Parâmetros

url

string

Uma cadeia de caracteres do cliente apontando para o serviço data lake do Armazenamento do Azure, como "https://myaccount.dfs.core.windows.net". Você pode acrescentar uma SAS se estiver usando AnonymousCredential, como "https://myaccount.dfs.core.windows.net?sasString".

pipeline
Pipeline

Chame newPipeline() para criar um pipeline padrão ou forneça um pipeline personalizado.

DataLakeServiceClient(string, StorageSharedKeyCredential | AnonymousCredential | TokenCredential, StoragePipelineOptions)

Cria uma instância de DataLakeServiceClient da URL.

new DataLakeServiceClient(url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)

Parâmetros

url

string

Uma cadeia de caracteres do cliente apontando para o serviço data lake do Armazenamento do Azure, como "https://myaccount.dfs.core.windows.net". Você pode acrescentar uma SAS se estiver usando AnonymousCredential, como "https://myaccount.dfs.core.windows.net?sasString".

credential

StorageSharedKeyCredential | AnonymousCredential | TokenCredential

Como AnonymousCredential, StorageSharedKeyCredential ou qualquer credencial do pacote @azure/identity para autenticar solicitações para o serviço. Você também pode fornecer um objeto que implementa a interface TokenCredential. Se não for especificado, AnonymousCredential será usado.

options
StoragePipelineOptions

Optional. Opções para configurar o pipeline HTTP.

Detalhes das propriedades herdadas

accountName

accountName: string

Valor da propriedade

string

herdado de StorageClient.accountName

credential

Como AnonymousCredential, StorageSharedKeyCredential ou qualquer credencial do pacote @azure/identity para autenticar solicitações para o serviço. Você também pode fornecer um objeto que implementa a interface TokenCredential. Se não for especificado, AnonymousCredential será usado.

credential: StorageSharedKeyCredential | AnonymousCredential | TokenCredential

Valor da propriedade

herdado de StorageClient.credential

url

Valor da cadeia de caracteres de URL codificada.

url: string

Valor da propriedade

string

herdado de StorageClient.url

Detalhes do método

fromConnectionString(string, StoragePipelineOptions)

Cria uma instância de DataLakeServiceClient da cadeia de conexão.

static function fromConnectionString(connectionString: string, options?: StoragePipelineOptions): DataLakeServiceClient

Parâmetros

connectionString

string

Cadeia de conexão de conta ou uma cadeia de conexão SAS de uma conta de armazenamento do Azure. [ Observação - A cadeia de conexão da conta só pode ser usada em NODE.JS runtime. ] Exemplo de cadeia de conexão da conta – DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net exemplo de cadeia de conexão SAS – BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString

options
StoragePipelineOptions

Optional. Opções para configurar o pipeline HTTP.

Retornos

generateAccountSasUrl(Date, AccountSASPermissions, string, ServiceGenerateAccountSasUrlOptions)

Disponível somente para DataLakeServiceClient construído com uma credencial de chave compartilhada.

Gera um URI de SAS (Assinatura de Acesso Compartilhado) de conta com base nas propriedades e parâmetros do cliente passados. A SAS é assinada pela credencial de chave compartilhada do cliente.

Consulte https://learn.microsoft.com/rest/api/storageservices/create-account-sas

function generateAccountSasUrl(expiresOn?: Date, permissions?: AccountSASPermissions, resourceTypes?: string, options?: ServiceGenerateAccountSasUrlOptions): string

Parâmetros

expiresOn

Date

Optional. O momento em que a assinatura de acesso compartilhado se torna inválida. Padrão para uma hora depois, se não especificado.

permissions
AccountSASPermissions

Especifica a lista de permissões a serem associadas à SAS.

resourceTypes

string

Especifica os tipos de recurso associados à assinatura de acesso compartilhado.

options
ServiceGenerateAccountSasUrlOptions

Parâmetros opcionais.

Retornos

string

Um URI SAS de conta que consiste no URI para o recurso representado por esse cliente, seguido pelo token SAS gerado.

generateSasStringToSign(Date, AccountSASPermissions, string, ServiceGenerateAccountSasUrlOptions)

Disponível somente para DataLakeServiceClient construído com uma credencial de chave compartilhada.

Gera uma cadeia de caracteres para assinar uma SAS (Assinatura de Acesso Compartilhado) de conta com base nas propriedades e parâmetros do cliente passados. A SAS é assinada pela credencial de chave compartilhada do cliente.

Consulte https://learn.microsoft.com/rest/api/storageservices/create-account-sas

function generateSasStringToSign(expiresOn?: Date, permissions?: AccountSASPermissions, resourceTypes?: string, options?: ServiceGenerateAccountSasUrlOptions): string

Parâmetros

expiresOn

Date

Optional. O momento em que a assinatura de acesso compartilhado se torna inválida. Padrão para uma hora depois, se não especificado.

permissions
AccountSASPermissions

Especifica a lista de permissões a serem associadas à SAS.

resourceTypes

string

Especifica os tipos de recurso associados à assinatura de acesso compartilhado.

options
ServiceGenerateAccountSasUrlOptions

Parâmetros opcionais.

Retornos

string

Um URI SAS de conta que consiste no URI para o recurso representado por esse cliente, seguido pelo token SAS gerado.

getFileSystemClient(string)

Cria um objeto DataLakeFileSystemClient.

function getFileSystemClient(fileSystemName: string): DataLakeFileSystemClient

Parâmetros

fileSystemName

string

Nome do sistema de arquivos.

Retornos

getProperties(ServiceGetPropertiesOptions)

Obtém as propriedades do ponto de extremidade do serviço Blob de uma conta de armazenamento, incluindo propriedades para as regras de Análise de Armazenamento e CORS (Compartilhamento de Recursos entre Origens).

Consulte https://learn.microsoft.com/rest/api/storageservices/get-blob-service-properties

function getProperties(options?: ServiceGetPropertiesOptions): Promise<ServiceGetPropertiesResponse>

Parâmetros

options
ServiceGetPropertiesOptions

Opções para a operação Obter Propriedades do Serviço.

Retornos

Dados de resposta para a operação Service Get Properties.

getUserDelegationKey(Date, Date, ServiceGetUserDelegationKeyOptions)

DISPONÍVEL SOMENTE AO USAR A AUTENTICAÇÃO DE TOKEN DE PORTADOR (TokenCredential).

Recupera uma chave de delegação do usuário para o serviço Data Lake. Essa é apenas uma operação válida ao usar a autenticação de token de portador.

Example

import {
  DataLakeServiceClient,
  generateDataLakeSASQueryParameters,
  FileSystemSASPermissions,
  SASProtocol,
} from "@azure/storage-file-datalake";

const account = "<account>";
const sas = "<sas token>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net${sas}`,
);

const fileSystemName = "<file system name>";
const accountName = "<account name>";
const startsOn = new Date();
const expiresOn = new Date(+new Date() + 86400 * 1000);
// Generate user delegation SAS for a file system
const userDelegationKey = await datalakeServiceClient.getUserDelegationKey(startsOn, expiresOn);
const fileSystemSAS = generateDataLakeSASQueryParameters(
  {
    fileSystemName, // Required
    permissions: FileSystemSASPermissions.parse("racwdl"), // Required
    startsOn, // Required. Date type
    expiresOn, // Optional. Date type
    ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional
    protocol: SASProtocol.HttpsAndHttp, // Optional
    version: "2018-11-09", // Must greater than or equal to 2018-11-09 to generate user delegation SAS
  },
  userDelegationKey, // UserDelegationKey
  accountName,
).toString();

Consulte https://learn.microsoft.com/rest/api/storageservices/get-user-delegation-key

function getUserDelegationKey(startsOn: Date, expiresOn: Date, options?: ServiceGetUserDelegationKeyOptions): Promise<ServiceGetUserDelegationKeyResponse>

Parâmetros

startsOn

Date

A hora de início da SAS de delegação do usuário. Deve estar dentro de 7 dias da hora atual.

expiresOn

Date

A hora de término da SAS de delegação do usuário. Deve estar dentro de 7 dias da hora atual.

Retornos

listFileSystems(ServiceListFileSystemsOptions)

Retorna um iterador iterável assíncrono para listar todos os sistemas de arquivos na conta especificada.

.byPage() retorna um iterador iterável assíncrono para listar os sistemas de arquivos em páginas.

Exemplo usando for await sintaxe:

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
const fileSystems = datalakeServiceClient.listFileSystems();
for await (const fileSystem of fileSystems) {
  console.log(`File system ${i++}: ${fileSystem.name}`);
}

Exemplo usando iter.next():

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
const fileSystems = datalakeServiceClient.listFileSystems();
let { value, done } = await fileSystems.next();
while (!done) {
  console.log(`File system ${i++}: ${value.name}`);
  ({ value, done } = await fileSystems.next());
}

Exemplo usando byPage():

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
for await (const response of datalakeServiceClient.listFileSystems().byPage({ maxPageSize: 20 })) {
  if (response.fileSystemItems) {
    for (const fileSystem of response.fileSystemItems) {
      console.log(`File System ${i++}: ${fileSystem.name}`);
    }
  }
}

Exemplo usando a paginação com um marcador:

import { DataLakeServiceClient } from "@azure/storage-file-datalake";
import { DefaultAzureCredential } from "@azure/identity";

const account = "<account>";
const datalakeServiceClient = new DataLakeServiceClient(
  `https://${account}.dfs.core.windows.net`,
  new DefaultAzureCredential(),
);

let i = 1;
let fileSystems = datalakeServiceClient.listFileSystems().byPage({ maxPageSize: 2 });
let response = (await fileSystems.next()).value;
// Prints 2 file systems
if (response.fileSystemItems) {
  for (const fileSystem of response.fileSystemItems) {
    console.log(`File system ${i++}: ${fileSystem.name}`);
  }
}
// Gets next marker
let marker = response.continuationToken;
// Passing next marker as continuationToken
fileSystems = datalakeServiceClient
  .listFileSystems()
  .byPage({ continuationToken: marker, maxPageSize: 10 });
response = (await fileSystems.next()).value;
// Prints 10 file systems
if (response.fileSystemItems) {
  for (const fileSystem of response.fileSystemItems) {
    console.log(`File system ${i++}: ${fileSystem.name}`);
  }
}

Consulte https://learn.microsoft.com/rest/api/storageservices/list-containers2

function listFileSystems(options?: ServiceListFileSystemsOptions): PagedAsyncIterableIterator<FileSystemItem, ServiceListFileSystemsSegmentResponse, PageSettings>

Parâmetros

Retornos

setProperties(BlobServiceProperties, ServiceSetPropertiesOptions)

Define propriedades para o ponto de extremidade do serviço Blob de uma conta de armazenamento, incluindo propriedades para análise de armazenamento, regras cors (compartilhamento de recursos entre origens) e configurações de exclusão reversível.

Consulte https://learn.microsoft.com/rest/api/storageservices/set-blob-service-properties

function setProperties(properties: BlobServiceProperties, options?: ServiceSetPropertiesOptions): Promise<ServiceSetPropertiesResponse>

Parâmetros

options
ServiceSetPropertiesOptions

Opções para a operação Propriedades do Conjunto de Serviços.

Retornos

Dados de resposta para a operação Propriedades do Conjunto de Serviços.

undeleteFileSystem(string, string, ServiceUndeleteFileSystemOptions)

Restaurar um sistema de arquivos excluído anteriormente. Essa API só estará funcional se a Exclusão Reversível do Contêiner estiver habilitada para a conta de armazenamento.

function undeleteFileSystem(deletedFileSystemName: string, deleteFileSystemVersion: string, options?: ServiceUndeleteFileSystemOptions): Promise<{ fileSystemClient: DataLakeFileSystemClient, fileSystemUndeleteResponse: ContainerUndeleteResponse }>

Parâmetros

deletedFileSystemName

string

O nome do sistema de arquivos de origem.

deleteFileSystemVersion

string

O novo nome do Sistema de Arquivos.

options
ServiceUndeleteFileSystemOptions

Opções para configurar a operação de Restauração do Sistema de Arquivos.

Retornos

Promise<{ fileSystemClient: DataLakeFileSystemClient, fileSystemUndeleteResponse: ContainerUndeleteResponse }>