Azure Data Lake Storage (ADLS) 包含所有必要的功能,讓開發人員、數據科學家和分析師輕鬆地儲存任何大小、形狀和速度的數據,以及跨平臺和語言執行所有類型的處理和分析。 它會移除擷取和儲存所有數據的複雜性,同時加快使用批次、串流和互動式分析啟動和執行的速度。
此專案提供 JavaScript 中的用戶端連結庫,可讓您輕鬆地取用 azure Storage Data Lake 服務Microsoft。
使用此套件中的用戶端連結庫來:
- 建立/列出/刪除文件系統
- 建立/讀取/清單/更新/刪除路徑、目錄和檔案
關鍵鏈接:
入門指南
目前支持的環境
- LTS 版本的 Node.js
- 最新版的 Safari、Chrome、Edge 和 Firefox。
如需詳細資訊,請參閱我們的支援原則。
Prerequisites
安裝套件
安裝適用於 JavaScript 的 Azure Storage Data Lake 用戶端連結庫的慣用方式是使用 npm 套件管理員。 在終端機視窗中輸入下列內容:
npm install @azure/storage-file-datalake
驗證用戶端
Azure 記憶體支援數種方式進行驗證。 若要與 Azure Data Lake Storage 服務互動,您必須建立記憶體用戶端的實例,例如 DataLakeServiceClient、DataLakeFileSystemClient或 DataLakePathClient。 請參閱建立
Azure Active Directory
Azure Data Lake Storage 服務支援使用 Azure Active Directory 來驗證其 API 的要求。
@azure/identity 套件提供應用程式可用來執行這項作業的各種認證類型。 如需詳細資訊和範例,請參閱 自述檔以取得 @azure/identity 以取得您的入門。
Compatibility
此連結庫與 Node.js 和瀏覽器相容,並針對 LTS Node.js 版本(>=8.16.0) 和最新版的 Chrome、Firefox 和 Edge 進行驗證。
Web Workers
此連結庫需要某些 DOM 對象在瀏覽器中使用時全域可用,Web 背景工作角色預設不會提供這些物件。 您必須進行聚合填入,才能讓此連結庫在 Web 背景工作。
如需詳細資訊,請參閱我們的 檔,以在 Web 背景工作角色中使用適用於 JS 的 Azure SDK
此連結庫取決於下列 DOM API,這些 API 需要在 Web 背景工作角色中使用時載入外部 polyfill:
Node.js 與瀏覽器之間的差異
Node.js 和瀏覽器運行時間之間有差異。 開始使用此連結庫時,請注意標示為「僅適用於NODE.JS運行時間」API 或類別, 或 「只能在瀏覽器中使用」。
- 如果檔案以
gzip或deflate格式保存壓縮的數據,且其內容編碼會據以設定,則下載行為在 Node.js 和瀏覽器之間會有所不同。 在 Node.js 記憶體用戶端會下載其壓縮格式的檔案,而在瀏覽器中,數據會以解壓縮格式下載。
功能、介面、類別或函式僅適用於 Node.js
- 根據帳戶名稱和帳戶金鑰的共用金鑰授權
StorageSharedKeyCredential
- 共用存取簽章(SAS) 產生
generateAccountSASQueryParameters()generateDataLakeSASQueryParameters()
- 平行上傳和下載。 請注意,Node.js 和瀏覽器都提供
DataLakeFileClient.upload()。DataLakeFileClient.uploadFile()DataLakeFileClient.uploadStream()DataLakeFileClient.readToBuffer()DataLakeFileClient.readToFile()
功能、介面、類別或函式僅適用於瀏覽器
- N/A
JavaScript 套件組合
若要在瀏覽器中使用此用戶端連結庫,您必須先使用配套程式。 有關如何執行此操作的詳細信息,請參閱我們的 捆綁文件。
CORS
如果您需要為瀏覽器進行開發,您必須為記憶體帳戶設定 跨原始資源分享 (CORS) 規則。 移至 Azure 入口網站和 Azure 記憶體總管,尋找您的記憶體帳戶,為 Blob/佇列/檔案/資料表服務建立新的 CORS 規則。
例如,您可以建立下列 CORS 設定以進行偵錯。 但請根據您的生產環境中的需求,仔細自定義設定。
- 允許的來源: *
- 允許的動詞:DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
- 允許的標頭: *
- 公開的標頭: *
- 年齡上限(秒):86400
注意:Data Lake 目前共用 Blob 服務的 CORS 設定。
重要概念
Azure Data Lake Storage Gen2 的設計目的是:
- 提供數 PB 的資訊,同時維持數百 GB 的輸送量
- 可讓您輕鬆管理大量數據
DataLake Storage Gen2 的主要功能包括:
- Hadoop 相容存取
- 一組超級 POSIX 許可權
- 在低成本儲存容量和交易方面符合成本效益
- 巨量數據分析的優化驅動程式
Data Lake Storage Gen2 的基本部分是將階層命名空間新增至 Blob 記憶體。 階層命名空間會將物件/檔案組織成目錄階層,以有效率地存取數據。
過去,雲端式分析在效能、管理和安全性方面必須妥協。 Data Lake Storage Gen2 會以下列方式解決上述每個層面:
- 效能已優化,因為您不需要複製或轉換數據作為分析的必要條件。 階層命名空間可大幅改善目錄管理作業的效能,進而改善整體作業效能。
- 管理比較容易,因為您可以透過目錄和子目錄來組織和操作檔案。
- 安全性是可強制執行的,因為您可以定義目錄或個別檔案的 POSIX 許可權。
- 由於 Data Lake Storage Gen2 建置在低成本的 Azure Blob 記憶體之上,因此可達到成本效益。 其他功能可進一步降低在 Azure 上執行巨量數據分析的總擁有成本。
Data Lake Storage 提供三種類型的資源:
-
透過
DataLakeServiceClient - 儲存體帳戶中的 檔案系統 ,透過
DataLakeFileSystemClient - 檔案系統
DataLakeDirectoryClient中的路徑,透過 或DataLakeFileClient
| Azure DataLake Gen2 | Blob |
|---|---|
| Filesystem | Container |
| 路徑 (檔案或目錄) | Blob |
注意:此用戶端連結庫僅支援已啟用階層命名空間 (HNS) 的記憶體帳戶。
Examples
- 匯入套件
- 建立 Data Lake Service 用戶端
- 建立新的文件系統
- 列出文件系統
- 建立和刪除目錄
- 建立檔案
- 檔案系統內的清單路徑
- 下載檔案,並將其轉換成字串 (Node.js)
- 下載檔案並將其轉換成字串 (瀏覽器)
匯入套件
若要使用用戶端,請將套件匯入您的檔案:
import * as AzureStorageDataLake from "@azure/storage-file-datalake";
或者,選擇性地只匯入您需要的類型:
import { DataLakeServiceClient, StorageSharedKeyCredential } from "@azure/storage-file-datalake";
建立 Data Lake Service 用戶端
DataLakeServiceClient 需要 Data Lake 服務的 URL 和存取認證。 它也會選擇性地接受 options 參數中的一些設定。
從 DefaultAzureCredential 套件使用 @azure/identity
具現化 DataLakeServiceClient 的建議方式
Notice. Azure Data Lake 目前會在下列 AAD OAuth 驗證期間重複使用 Blob 相關角色,例如「記憶體 Blob 數據擁有者」。
設定:參考 - 從用戶端應用程式使用 Azure Active Directory 授權訪問 blob(數據湖)和佇列 - https://learn.microsoft.com/azure/storage/common/storage-auth-aad-app
註冊新的 AAD 應用程式,並授與代表登入使用者存取 Azure 記憶體的許可權。
- 在 Azure Active Directory 中註冊新應用程式(在 azure-portal 中) - https://learn.microsoft.com/azure/active-directory/develop/quickstart-register-app
- 在 [
API permissions] 區段中,選取 [Add a permission],然後選擇 [Microsoft APIs]。 - 挑選
Azure Storage,然後選取user_impersonation旁的複選框,然後按兩下 [Add permissions]。 這可讓應用程式代表登入的使用者存取 Azure 記憶體。
在 Azure 入口網站中使用 RBAC 授與 Azure Data Lake 數據的存取權
- blob(數據湖)和佇列的 RBAC 角色 - https://learn.microsoft.com/azure/storage/common/storage-auth-aad-rbac-portal.
- 在 Azure 入口網站中,移至您的記憶體帳戶,並將 儲存體 Blob 數據參與者 角色指派給已註冊的 AAD 應用程式,從 [
Access control (IAM)] 索引標籤(在 azure-portal 中記憶體帳戶的左側導覽列中)。
範例的環境設定
- 從 AAD 應用程式的概觀頁面,記下
CLIENT ID和TENANT ID。 在 [憑證 & 秘密] 索引標籤中,建立秘密並記下。 - 請確定您有AZURE_TENANT_ID、AZURE_CLIENT_ID AZURE_CLIENT_SECRET作為環境變數,才能成功執行範例(Can 利用 process.env)。
- 從 AAD 應用程式的概觀頁面,記下
import { DefaultAzureCredential } from "@azure/identity";
import { DataLakeServiceClient } from "@azure/storage-file-datalake";
// Enter your storage account name
const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();
const datalakeServiceClient = new DataLakeServiceClient(
`https://${account}.dfs.core.windows.net`,
defaultAzureCredential,
);
如需使用此方法的完整範例,請參閱 Azure AD 驗證範例。
[注意 - 上述步驟僅適用於 Node.js]
使用連接字串
或者,您可以使用具有完整連接字串做為自變數的 DataLakeServiceClient 靜態方法,具現化 fromConnectionString()。 (您可以從 Azure 入口網站取得連接字串。[僅適用於NODE.JS運行時間]
import { DataLakeServiceClient } from "@azure/storage-file-datalake";
const connectionString = "<connection string>";
const dataLakeServiceClient = DataLakeServiceClient.fromConnectionString(connectionString);
搭配 StorageSharedKeyCredential
或者,您可以藉由傳遞 account-name 和 account-key 作為自變數,以 DataLakeServiceClient 具現化 StorageSharedKeyCredential。 (帳戶名稱和帳戶密鑰可以從 Azure 入口網站取得。[僅適用於NODE.JS運行時間]
import { StorageSharedKeyCredential, DataLakeServiceClient } from "@azure/storage-file-datalake";
// Enter your storage account name and shared key
const account = "<account>";
const accountKey = "<accountkey>";
// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
const datalakeServiceClient = new DataLakeServiceClient(
`https://${account}.dfs.core.windows.net`,
sharedKeyCredential,
);
使用SAS令牌
此外,您可以使用共用存取簽章來具現化 DataLakeServiceClient(SAS)。 您可以從 Azure 入口網站取得 SAS 令牌,或使用 generateAccountSASQueryParameters()產生。
import { DataLakeServiceClient } from "@azure/storage-file-datalake";
const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const serviceClientWithSAS = new DataLakeServiceClient(
`https://${account}.dfs.core.windows.net${sas}`,
);
建立新的文件系統
使用 DataLakeServiceClient.getFileSystemClient() 取得文件系統用戶端實例,然後建立新的文件系統資源。
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(),
);
// Create a file system
const fileSystemName = `newfilesystem${new Date().getTime()}`;
const fileSystemClient = datalakeServiceClient.getFileSystemClient(fileSystemName);
const createResponse = await fileSystemClient.create();
console.log(`Create file system ${fileSystemName} successfully`, createResponse.requestId);
列出檔案系統
使用 DataLakeServiceClient.listFileSystems() 函式來反覆運算檔案系統,並搭配新的 for-await-of 語法:
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}`);
}
或者,不使用 for-await-of:
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());
}
此外,也支援透過 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}`);
}
}
}
建立和刪除目錄
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(),
);
const fileSystemName = "<file system name>";
const fileSystemClient = datalakeServiceClient.getFileSystemClient(fileSystemName);
const directoryClient = fileSystemClient.getDirectoryClient("directory");
await directoryClient.create();
await directoryClient.delete();
建立檔案
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(),
);
const fileSystemName = "<file system name>";
const fileSystemClient = datalakeServiceClient.getFileSystemClient(fileSystemName);
const content = "Hello world!";
const fileName = `newfile${+new Date()}`;
const fileClient = fileSystemClient.getFileClient(fileName);
await fileClient.create();
await fileClient.append(content, 0, content.length);
await fileClient.flush(content.length);
console.log(`Create and upload file ${fileName} successfully`);
列出檔案系統內的路徑
類似於列出文件系統。
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(),
);
const fileSystemName = "<file system name>";
const fileSystemClient = datalakeServiceClient.getFileSystemClient(fileSystemName);
let i = 1;
const paths = fileSystemClient.listPaths();
for await (const path of paths) {
console.log(`Path ${i++}: ${path.name}, is directory: ${path.isDirectory}`);
}
下載檔案並將它轉換成字串 (Node.js)
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(),
);
const fileSystemName = "<file system name>";
const fileName = "<file name>";
const fileSystemClient = datalakeServiceClient.getFileSystemClient(fileSystemName);
const fileClient = fileSystemClient.getFileClient(fileName);
// Get file content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadResponse.readableStreamBody
const downloadResponse = await fileClient.read();
if (downloadResponse.readableStreamBody) {
const downloaded = await streamToBuffer(downloadResponse.readableStreamBody);
console.log("Downloaded file content:", downloaded.toString());
}
// [Node.js only] A helper method used to read a Node.js readable stream into a Buffer.
async function streamToBuffer(readableStream: NodeJS.ReadableStream): Promise<Buffer> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
readableStream.on("data", (data) => {
chunks.push(data instanceof Buffer ? data : Buffer.from(data));
});
readableStream.on("end", () => {
resolve(Buffer.concat(chunks));
});
readableStream.on("error", reject);
});
}
下載檔案並將轉換為字串 (瀏覽器)
import { DataLakeServiceClient } 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 fileName = "<file name>";
const fileSystemClient = datalakeServiceClient.getFileSystemClient(fileSystemName);
const fileClient = fileSystemClient.getFileClient(fileName);
// Get file content from position 0 to the end
// In browsers, get downloaded data by accessing downloadResponse.contentAsBlob
const downloadResponse = await fileClient.read();
if (downloadResponse.contentAsBlob) {
const blob = await downloadResponse.contentAsBlob;
const downloaded = await blob.text();
console.log(`Downloaded file content ${downloaded}`);
}
Troubleshooting
啟用記錄可能有助於找出有關失敗的實用資訊。 若要查看 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在運行時間啟用記錄,方法是在 setLogLevel中呼叫 @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
後續步驟
其他程式代碼範例:
Contributing
如果您想要參與此連結庫,請閱讀 參與指南 ,以深入瞭解如何建置和測試程序代碼。