使用 JavaScript 管理 Azure Data Lake Storage Gen2 中的目录、文件和 ACLUse JavaScript to manage directories, files, and ACLs in Azure Data Lake Storage Gen2

本文介绍了如何使用 JavaScript 在启用了分层命名空间 (HNS) 的存储帐户中创建和管理目录、文件与权限。This article shows you how to use JavaScript to create and manage directories, files, and permissions in storage accounts that has hierarchical namespace (HNS) enabled.

包(节点包管理器)” | ”示例” | ”提供反馈Package (Node Package Manager) | Samples | Give Feedback

先决条件Prerequisites

  • Azure 订阅。An Azure subscription. 请参阅获取 Azure 试用版See Get Azure trial.
  • 一个已启用分层命名空间 (HNS) 的存储帐户。A storage account that has hierarchical namespace (HNS) enabled. 这些说明创建一个。Follow these instructions to create one.
  • 如果在 Node.js 应用程序中使用此包,则需要 Node.js 8.0.0 或更高版本。If you are using this package in a Node.js application, you'll need Node.js 8.0.0 or higher.

设置项目Set up your project

打开一个终端窗口,然后键入以下命令来安装适用于 JavaScript 的 Data Lake 客户端库。Install Data Lake client library for JavaScript by opening a terminal window, and then typing the following command.

npm install @azure/storage-file-datalake

将此语句放置在代码文件的顶部,以导入 storage-file-datalake 包。Import the storage-file-datalake package by placing this statement at the top of your code file.

const AzureStorageDataLake = require("@azure/storage-file-datalake");

连接到帐户Connect to the account

若要使用本文中的代码片段,需创建一个表示存储帐户的 DataLakeServiceClient 实例。To use the snippets in this article, you'll need to create a DataLakeServiceClient instance that represents the storage account.

使用帐户密钥进行连接Connect by using an account key

这是连接到帐户的最简单方法。This is the easiest way to connect to an account.

此示例使用帐户密钥创建 DataLakeServiceClient 实例。This example creates a DataLakeServiceClient instance by using an account key.


function GetDataLakeServiceClient(accountName, accountKey) {

  const sharedKeyCredential = 
     new StorageSharedKeyCredential(accountName, accountKey);
  
  const datalakeServiceClient = new DataLakeServiceClient(
      `https://${accountName}.dfs.core.chinacloudapi.cn`, sharedKeyCredential);

  return datalakeServiceClient;             
}      

备注

此授权方法仅适用于 Node.js 应用程序。This method of authorization works only for Node.js applications. 如果打算在浏览器中运行代码,则可以使用 Azure Active Directory (AD) 进行授权。If you plan to run your code in a browser, you can authorize by using Azure Active Directory (AD).

使用 Azure Active Directory (AD) 进行连接Connect by using Azure Active Directory (AD)

可以使用适用于 JS 的 Azure 标识客户端库,通过 Azure AD 对应用程序进行身份验证。You can use the Azure identity client library for JS to authenticate your application with Azure AD.

此示例使用客户端 ID、客户端密码和租户 ID 创建 DataLakeServiceClient 实例。This example creates a DataLakeServiceClient instance by using a client ID, a client secret, and a tenant ID. 若要获取这些值,请参阅从 Azure AD 获取用于请求客户端应用程序授权的令牌To get these values, see Acquire a token from Azure AD for authorizing requests from a client application.

function GetDataLakeServiceClientAD(accountName, clientID, clientSecret, tenantID) {

  const credential = new ClientSecretCredential(tenantID, clientID, clientSecret);
  
  const datalakeServiceClient = new DataLakeServiceClient(
      `https://${accountName}.dfs.core.chinacloudapi.cn`, credential);

  return datalakeServiceClient;             
}

备注

有关更多示例,请参阅适用于 JS 的 Azure 标识客户端库文档。For more examples, see the Azure identity client library for JS documentation.

创建容器Create a container

容器充当文件的文件系统。A container acts as a file system for your files. 可以通过获取 FileSystemClient 实例,然后调用 FileSystemClient.Create 方法来创建一个。You can create one by getting a FileSystemClient instance, and then calling the FileSystemClient.Create method.

此示例创建一个名为 my-file-system 的容器。This example creates a container named my-file-system.

async function CreateFileSystem(datalakeServiceClient) {

  const fileSystemName = "my-file-system";
  
  const fileSystemClient = datalakeServiceClient.getFileSystemClient(fileSystemName);

  const createResponse = await fileSystemClient.create();
        
}

创建目录Create a directory

可以通过获取 DirectoryClient 实例,然后调用 DirectoryClient.create 方法来创建目录引用。Create a directory reference by getting a DirectoryClient instance, and then calling the DirectoryClient.create method.

此示例将名为 my-directory 的目录添加到容器中。This example adds a directory named my-directory to a container.

async function CreateDirectory(fileSystemClient) {
   
  const directoryClient = fileSystemClient.getDirectoryClient("my-directory");
  
  await directoryClient.create();

}

重命名或移动目录Rename or move a directory

可以通过调用 DirectoryClient.rename 方法来重命名或移动目录。Rename or move a directory by calling the DirectoryClient.rename method. 以参数形式传递所需目录的路径。Pass the path of the desired directory a parameter.

此示例将某个子目录重命名为名称 my-directory-renamedThis example renames a sub-directory to the name my-directory-renamed.

async function RenameDirectory(fileSystemClient) {

  const directoryClient = fileSystemClient.getDirectoryClient("my-directory"); 
  await directoryClient.move("my-directory-renamed");

}

此示例将名为 my-directory-renamed 的目录移到名为 my-directory-2 的目录的子目录中。This example moves a directory named my-directory-renamed to a sub-directory of a directory named my-directory-2.

async function MoveDirectory(fileSystemClient) {

  const directoryClient = fileSystemClient.getDirectoryClient("my-directory-renamed"); 
  await directoryClient.move("my-directory-2/my-directory-renamed");      

}

删除目录Delete a directory

可以通过调用 DirectoryClient.delete 方法来删除目录。Delete a directory by calling the DirectoryClient.delete method.

此示例删除名为 my-directory 的目录。This example deletes a directory named my-directory.

async function DeleteDirectory(fileSystemClient) {

  const directoryClient = fileSystemClient.getDirectoryClient("my-directory"); 
  await directoryClient.delete();

}

将文件上传到目录Upload a file to a directory

首先,读取文件。First, read a file. 此示例使用 Node.js fs 模块。This example uses the Node.js fs module. 然后,通过创建一个 FileClient 实例并调用 FileClient.create 方法,在目标目录中创建文件引用。Then, create a file reference in the target directory by creating a FileClient instance, and then calling the FileClient.create method. 通过调用 FileClient.append 方法来上传文件。Upload a file by calling the FileClient.append method. 请确保通过调用 FileClient.flush 方法完成上传。Make sure to complete the upload by calling the FileClient.flush method.

此示例将文本文件上传到名为 my-directory 的目录。This example uploads a text file to a directory named my-directory.`

async function UploadFile(fileSystemClient) {

  const fs = require('fs') 

  var content = "";
  
  fs.readFile('mytestfile.txt', (err, data) => { 
      if (err) throw err; 

      content = data.toString();

  }) 
  
  const fileClient = fileSystemClient.getFileClient("my-directory/uploaded-file.txt");
  await fileClient.create();
  await fileClient.append(content, 0, content.length);
  await fileClient.flush(content.length);

}

从目录下载Download from a directory

首先,创建表示要下载的文件的一个 FileSystemClient 实例。First, create a FileSystemClient instance that represents the file that you want to download. 使用 FileSystemClient.read 方法读取该文件。Use the FileSystemClient.read method to read the file. 然后,写入该文件。Then, write the file. 此示例使用 Node.js fs 模块来执行该操作。This example uses the Node.js fs module to do that.

备注

此文件下载方法仅适用于 Node.js 应用程序。This method of downloading a file works only for Node.js applications. 如果打算在浏览器中运行代码,请参阅适用于 JavaScript 的 Azure Storage File Data Lake 客户端库自述文件来查看有关如何在浏览器中执行此操作的示例。If you plan to run your code in a browser, see the Azure Storage File Data Lake client library for JavaScript readme file for an example of how to do this in a browser.

async function DownloadFile(fileSystemClient) {

  const fileClient = fileSystemClient.getFileClient("my-directory/uploaded-file.txt");

  const downloadResponse = await fileClient.read();

  const downloaded = await streamToString(downloadResponse.readableStreamBody);
 
  async function streamToString(readableStream) {
    return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", (data) => {
        chunks.push(data.toString());
      });
      readableStream.on("end", () => {
        resolve(chunks.join(""));
      });
      readableStream.on("error", reject);
    });
  }   
  
  const fs = require('fs');

  fs.writeFile('mytestfiledownloaded.txt', downloaded, (err) => {
    if (err) throw err;
  });
}

列出目录内容List directory contents

此示例输出名为 my-directory 的目录中的每个目录和文件的名称。This example, prints the names of each directory and file that is located in a directory named my-directory.

async function ListFilesInDirectory(fileSystemClient) {
  
  let i = 1;

  let iter = await fileSystemClient.listPaths({path: "my-directory", recursive: true});

  for await (const path of iter) {
    
    console.log(`Path ${i++}: ${path.name}, is directory: ${path.isDirectory}`);
  }

}

管理访问控制列表 (ACL)Manage access control lists (ACLs)

可以获取、设置和更新目录与文件的访问权限。You can get, set, and update access permissions of directories and files.

备注

若要使用 Azure Active Directory (Azure AD) 来授予访问权限,请确保已为安全主体分配了存储 Blob 数据所有者角色If you're using Azure Active Directory (Azure AD) to authorize access, then make sure that your security principal has been assigned the Storage Blob Data Owner role. 若要详细了解如何应用 ACL 权限以及更改它们所带来的影响,请参阅 Azure Data Lake Storage Gen2 中的访问控制To learn more about how ACL permissions are applied and the effects of changing them, see Access control in Azure Data Lake Storage Gen2.

管理目录 ACLManage a directory ACL

此示例获取并设置名为 my-directory 的目录的 ACL。This example gets and then sets the ACL of a directory named my-directory. 此示例为拥有用户提供读取、写入和执行权限,为拥有组授予读取和执行权限,并为所有其他用户提供读取访问权限。This example gives the owning user read, write, and execute permissions, gives the owning group only read and execute permissions, and gives all others read access.

备注

如果你的应用程序通过使用 Azure Active Directory (Azure AD) 来授予访问权限,请确保已向应用程序用来授权访问的安全主体分配了存储 Blob 数据所有者角色If your application authorizes access by using Azure Active Directory (Azure AD), then make sure that the security principal that your application uses to authorize access has been assigned the Storage Blob Data Owner role. 若要详细了解如何应用 ACL 权限以及更改它们所带来的影响,请参阅 Azure Data Lake Storage Gen2 中的访问控制To learn more about how ACL permissions are applied and the effects of changing them, see Access control in Azure Data Lake Storage Gen2.

async function ManageDirectoryACLs(fileSystemClient) {

    const directoryClient = fileSystemClient.getDirectoryClient("my-directory"); 
    const permissions = await directoryClient.getAccessControl();

    console.log(permissions.acl);

    const acl = [
    {
      accessControlType: "user",
      entityId: "",
      defaultScope: false,
      permissions: {
        read: true,
        write: true,
        execute: true
      }
    },
    {
      accessControlType: "group",
      entityId: "",
      defaultScope: false,
      permissions: {
        read: true,
        write: false,
        execute: true
      }
    },
    {
      accessControlType: "other",
      entityId: "",
      defaultScope: false,
      permissions: {
        read: true,
        write: true,
        execute: false
      }

    }

  ];

  await directoryClient.setAccessControl(acl);
}

还可以获取和设置容器根目录的 ACL。You can also get and set the ACL of the root directory of a container. 若要获取根目录,请将空字符串 (/) 传递到“DataLakeFileSystemClient.getDirectoryClient”方法。To get the root directory, pass an empty string (/) into the DataLakeFileSystemClient.getDirectoryClient method.

管理文件 ACLManage a file ACL

此示例获取并设置名为 upload-file.txt 的文件的 ACL。This example gets and then sets the ACL of a file named upload-file.txt. 此示例为拥有用户提供读取、写入和执行权限,为拥有组授予读取和执行权限,并为所有其他用户提供读取访问权限。This example gives the owning user read, write, and execute permissions, gives the owning group only read and execute permissions, and gives all others read access.

备注

如果你的应用程序通过使用 Azure Active Directory (Azure AD) 来授予访问权限,请确保已向应用程序用来授权访问的安全主体分配了存储 Blob 数据所有者角色If your application authorizes access by using Azure Active Directory (Azure AD), then make sure that the security principal that your application uses to authorize access has been assigned the Storage Blob Data Owner role. 若要详细了解如何应用 ACL 权限以及更改它们所带来的影响,请参阅 Azure Data Lake Storage Gen2 中的访问控制To learn more about how ACL permissions are applied and the effects of changing them, see Access control in Azure Data Lake Storage Gen2.

async function ManageFileACLs(fileSystemClient) {

  const fileClient = fileSystemClient.getFileClient("my-directory/uploaded-file.txt"); 
  const permissions = await fileClient.getAccessControl();

  console.log(permissions.acl);

  const acl = [
  {
    accessControlType: "user",
    entityId: "",
    defaultScope: false,
    permissions: {
      read: true,
      write: true,
      execute: true
    }
  },
  {
    accessControlType: "group",
    entityId: "",
    defaultScope: false,
    permissions: {
      read: true,
      write: false,
      execute: true
    }
  },
  {
    accessControlType: "other",
    entityId: "",
    defaultScope: false,
    permissions: {
      read: true,
      write: true,
      execute: false
    }

  }

];

await fileClient.setAccessControl(acl);        
}

另请参阅See also