如何從 Node.js 使用 Azure 表格儲存體或 Azure Cosmos DB 資料表 APIHow to use Azure Table storage or the Azure Cosmos DB Table API from Node.js

適用於: 資料表 API

提示

本文中的內容適用於 Azure 資料表儲存體和 Azure Cosmos DB 資料表 API。The content in this article applies to Azure Table storage and the Azure Cosmos DB Table API. Azure Cosmos DB 資料表 API 是資料表儲存體的進階供應項目,可提供輸送量最佳化的資料表、全域發佈,以及自動次要索引。The Azure Cosmos DB Table API is a premium offering for table storage that offers throughput-optimized tables, global distribution, and automatic secondary indexes.

本文說明如何建立資料表、儲存您的資料,以及對資料執行 CRUD 作業。This article shows you how to create tables, store your data, and perform CRUD operations on the data. 選擇 Azure 資料表服務或 Azure Cosmos DB 資料表 API。Choose either the Azure Table service or the Azure Cosmos DB Table API. 範例是以 Node.js 撰寫的。The samples are written in Node.js.

建立 Azure 服務帳戶Create an Azure service account

您可以使用 Azure 表格儲存體或 Azure Cosmos DB 來搭配使用表格。You can work with tables using the Azure Table storage or the Azure Cosmos DB. 若要深入了解這兩項服務中的資料表供應項目間的差異,請參閱資料表供應項目一文。To learn more about the differences between table offerings in these two services, see the Table offerings article. 您必須為您要使用的服務建立帳戶。You'll need to create an account for the service you're going to use. 下列各節說明如何建立 Azure 資料表儲存體和 Azure Cosmos DB 帳戶,不過您可以只使用其中一個。The following sections show how to create both Azure Table storage and the Azure Cosmos DB account, however you can just use one of them.

建立 Azure 儲存體帳戶Create an Azure storage account

建立 Azure 儲存體帳戶最簡單的方法,就是使用 Azure 入口網站The easiest way to create an Azure storage account is by using the Azure portal. 若要深入了解,請參閱 建立儲存體帳戶To learn more, see Create a storage account.

您也可以使用 Azure PowerShellAzure CLI 來建立 Azure 儲存體帳戶。You can also create an Azure storage account by using Azure PowerShell or Azure CLI.

如果您不想在此時建立儲存體帳戶,也可以使用 Azure 儲存體模擬器在本機環境中執行並測試您的程式碼。If you prefer not to create a storage account at this time, you can also use the Azure Storage Emulator to run and test your code in a local environment. 如需詳細資訊,請參閱使用 Azure 儲存體模擬器進行開發和測試For more information, see Use the Azure Storage Emulator for development and testing.

建立 Azure Cosmos DB 表格 API 帳戶Create an Azure Cosmos DB Table API account

有關建立 Azure Cosmos DB 資料表 API 帳戶的指示,請參閱建立表格資料庫帳戶For instructions on creating an Azure Cosmos DB Table API account, see Create a database account.

設定您的應用程式以存取 Azure 儲存體或 Azure Cosmos DB 資料表 APIConfigure your application to access Azure Storage or the Azure Cosmos DB Table API

若要使用 Azure 儲存體或 Azure Cosmos DB,您需要 Azure Storage SDK for Node.js,這包含一組能與「儲存體 REST」服務進行通訊的便利程式庫。To use Azure Storage or Azure Cosmos DB, you need the Azure Storage SDK for Node.js, which includes a set of convenience libraries that communicate with the Storage REST services.

使用 Node Package Manager (NPM) 安裝封裝Use Node Package Manager (NPM) to install the package

  1. 使用命令列介面,例如 PowerShell (Windows)、終端機 (Mac) 或 Bash (Unix),瀏覽至儲存所建立應用程式的資料夾。Use a command-line interface such as PowerShell (Windows), Terminal (Mac), or Bash (Unix), and navigate to the folder where you created your application.

  2. 在命令視窗中輸入 npm install azure-storageType npm install azure-storage in the command window. 此命令的輸出類似下列範例。Output from the command is similar to the following example.

     azure-storage@0.5.0 node_modules\azure-storage
     +-- extend@1.2.1
     +-- xmlbuilder@0.4.3
     +-- mime@1.2.11
     +-- node-uuid@1.4.3
     +-- validator@3.22.2
     +-- underscore@1.4.4
     +-- readable-stream@1.0.33 (string_decoder@0.10.31, isarray@0.0.1, inherits@2.0.1, core-util-is@1.0.1)
     +-- xml2js@0.2.7 (sax@0.5.2)
     +-- request@2.57.0 (caseless@0.10.0, aws-sign2@0.5.0, forever-agent@0.6.1, stringstream@0.0.4, oauth-sign@0.8.0, tunnel-agent@0.4.1, isstream@0.1.2, json-stringify-safe@5.0.1, bl@0.9.4, combined-stream@1.0.5, qs@3.1.0, mime-types@2.0.14, form-data@0.2.0, http-signature@0.11.0, tough-cookie@2.0.0, hawk@2.3.1, har-validator@1.8.0)
    
  3. 您可以手動執行 ls 命令,確認已建立 node_modules 資料夾。You can manually run the ls command to verify that a node_modules folder was created. 該資料夾中有 azure-storage 封裝,當中包含存取儲存體所需的程式庫。Inside that folder you will find the azure-storage package, which contains the libraries you need to access storage.

匯入封裝Import the package

將下列程式碼加在應用程式中的 server.js 檔案之上:Add the following code to the top of the server.js file in your application:

var azure = require('azure-storage');

新增連接字串Add your connection string

您可以連線到 Azure 儲存體帳戶或 Azure Cosmos DB 資料表 API 帳戶。You can either connect to the Azure storage account or the Azure Cosmos DB Table API account. 根據您使用的帳戶類型,取得連接字串。Get the connection string based on the type of account you are using.

新增 Azure 儲存體連線Add an Azure Storage connection

Azure 模組會讀取環境變數 AZURE_STORAGE_ACCOUNT 和 AZURE_STORAGE_ACCESS_KEY 或 AZURE_STORAGE_CONNECTION_STRING,以取得連線至「Azure 儲存體帳戶」所需的資訊。The Azure module reads the environment variables AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY, or AZURE_STORAGE_CONNECTION_STRING for information required to connect to your Azure Storage account. 如果未設定這些環境變數,則呼叫 TableService 時必須指定帳戶資訊。If these environment variables are not set, you must specify the account information when calling TableService. 例如,下列程式碼會建立 TableService 物件:For example, the following code creates a TableService object:

var tableSvc = azure.createTableService('myaccount', 'myaccesskey');

新增 Azure Cosmos DB 連線Add an Azure Cosmos DB connection

若要新增 Azure Cosmos DB 連線,請建立 TableService 物件,然後指定您的帳戶名稱、主要索引鍵及端點。To add an Azure Cosmos DB connection, create a TableService object and specify your account name, primary key, and endpoint. 您可以在 Azure 入口網站中,從您 Cosmos DB 的 [設定] > [連接字串] 中複製這些值。You can copy these values from Settings > Connection String in the Azure portal for your Cosmos DB account. 例如:For example:

var tableSvc = azure.createTableService('myaccount', 'myprimarykey', 'myendpoint');

建立資料表Create a table

下列程式碼會建立 TableService 物件,並使用該物件建立新資料表。The following code creates a TableService object and uses it to create a new table.

var tableSvc = azure.createTableService();

呼叫 createTableIfNotExists 時,會以指定的名稱建立新的資料表 (若此資料表尚未存在)。The call to createTableIfNotExists creates a new table with the specified name if it does not already exist. 如果名為 'mytable' 的資料表尚不存在,下列範例便會建立這個新資料表:The following example creates a new table named 'mytable' if it does not already exist:

tableSvc.createTableIfNotExists('mytable', function(error, result, response){
  if(!error){
    // Table exists or created
  }
});

如果是建立新資料表,result.created 會是 true,如果資料表已存在,則為 falseThe result.created is true if a new table is created, and false if the table already exists. response 會包含要求的相關資訊。The response contains information about the request.

套用篩選條件Apply filters

您可以將選用的篩選套用到使用 TableService 來執行的作業。You can apply optional filtering to operations performed using TableService. 篩選作業可包括記錄、自動重試等。篩選器是使用簽章實作方法的物件:Filtering operations can include logging, automatic retries, etc. Filters are objects that implement a method with the signature:

function handle (requestOptions, next)

在對要求選項進行前處理之後,方法必須呼叫 next,傳遞具有下列簽章的回呼:After doing its preprocessing on the request options, the method must call next, passing a callback with the following signature:

function (returnObject, finalCallback, next)

在此回呼中,以及處理 returnObject (來自對伺服器之要求的回應) 之後,回呼必須叫用 next (如果存在) 以繼續處理其他篩選器,或是直接叫用 finalCallback 以結束服務叫用。In this callback, and after processing the returnObject (the response from the request to the server), the callback must either invoke next if it exists to continue processing other filters or simply invoke finalCallback otherwise to end the service invocation.

Azure SDK for Node.js 包含了兩個實作重試邏輯的篩選器: ExponentialRetryPolicyFilterLinearRetryPolicyFilterTwo filters that implement retry logic are included with the Azure SDK for Node.js, ExponentialRetryPolicyFilter and LinearRetryPolicyFilter. 下列會建立使用 ExponentialRetryPolicyFilterTableService 物件:The following creates a TableService object that uses the ExponentialRetryPolicyFilter:

var retryOperations = new azure.ExponentialRetryPolicyFilter();
var tableSvc = azure.createTableService().withFilter(retryOperations);

將實體新增至資料表Add an entity to a table

若要新增實體,請先建立一個定義實體屬性的物件。To add an entity, first create an object that defines your entity properties. 所有實體必須包含 PartitionKeyRowKey,這些是實體的唯一識別碼。All entities must contain a PartitionKey and RowKey, which are unique identifiers for the entity.

  • PartitionKey - 可決定儲存實體的分割區。PartitionKey - Determines the partition in which the entity is stored.
  • RowKey - 可在分割區內唯一地識別實體。RowKey - Uniquely identifies the entity within the partition.

PartitionKeyRowKey 都必須是字串值。Both PartitionKey and RowKey must be string values. 如需詳細資訊,請參閱 了解表格服務資料模型For more information, see Understanding the Table Service Data Model.

以下是定義實體的範例。The following is an example of defining an entity. dueDate 定義為 Edm.DateTime 的類型。The dueDate is defined as a type of Edm.DateTime. 您可以視需要指定類型,若未指定,系統就會推斷類型。Specifying the type is optional, and types are inferred if not specified.

var task = {
  PartitionKey: {'_':'hometasks'},
  RowKey: {'_': '1'},
  description: {'_':'take out the trash'},
  dueDate: {'_':new Date(2015, 6, 20), '$':'Edm.DateTime'}
};

注意

每筆記錄還有 Timestamp 欄位,插入或更新實體時,Azure 會設定此欄位。There is also a Timestamp field for each record, which is set by Azure when an entity is inserted or updated.

您也可以使用 entityGenerator 來建立實體。You can also use the entityGenerator to create entities. 下列範例使用 entityGenerator 建立相同的工作實體。The following example creates the same task entity using the entityGenerator.

var entGen = azure.TableUtilities.entityGenerator;
var task = {
  PartitionKey: entGen.String('hometasks'),
  RowKey: entGen.String('1'),
  description: entGen.String('take out the trash'),
  dueDate: entGen.DateTime(new Date(Date.UTC(2015, 6, 20))),
};

若要將實體新增至資料表,請將實體物件傳給 insertEntity 方法。To add an entity to your table, pass the entity object to the insertEntity method.

tableSvc.insertEntity('mytable',task, function (error, result, response) {
  if(!error){
    // Entity inserted
  }
});

如果作業成功,result 就會包含所插入記錄的 ETag,而 response 則會包含作業的相關資訊。If the operation is successful, result contains the ETag of the inserted record and response contains information about the operation.

範例回應:Example response:

{ '.metadata': { etag: 'W/"datetime\'2015-02-25T01%3A22%3A22.5Z\'"' } }

注意

根據預設,insertEntity 不會將已插入的實體包含在 response 資訊中傳回。By default, insertEntity does not return the inserted entity as part of the response information. 若您打算對此實體執行其他作業,或想要快取資訊,則將此實體包含在 result 中傳回會相當有用。If you plan on performing other operations on this entity, or want to cache the information, it can be useful to have it returned as part of the result. 您可以啟用 echoContent 來達成目的,如下所示:You can do this by enabling echoContent as follows:

tableSvc.insertEntity('mytable', task, {echoContent: true}, function (error, result, response) {...}

更新實體Update an entity

有多種方法可以用來更新現有的實體:There are multiple methods available to update an existing entity:

  • replaceEntity - 藉由取代現有實體來更新現有實體。replaceEntity - Updates an existing entity by replacing it.
  • mergeEntity - 藉由將新的屬性值合併到現有實體來更新現有實體。mergeEntity - Updates an existing entity by merging new property values into the existing entity.
  • insertOrReplaceEntity - 藉由取代現有實體來更新現有實體。insertOrReplaceEntity - Updates an existing entity by replacing it. 如果實體不存在,將會插入新的實體。If no entity exists, a new one will be inserted.
  • insertOrMergeEntity - 藉由將新的屬性值合併到現有實體來更新現有項目。insertOrMergeEntity - Updates an existing entity by merging new property values into the existing. 如果實體不存在,將會插入新的實體。If no entity exists, a new one will be inserted.

下列範例示範使用 replaceEntity 來更新實體:The following example demonstrates updating an entity using replaceEntity:

tableSvc.replaceEntity('mytable', updatedTask, function(error, result, response){
  if(!error) {
    // Entity updated
  }
});

注意

依預設,更新實體並不會檢查正在更新的資料先前是否被另一個程序修改過。By default, updating an entity does not check to see if the data being updated has previously been modified by another process. 若要支援並行更新:To support concurrent updates:

  1. 取得正在更新之物件的 ETag。Get the ETag of the object being updated. 系統會針對實體相關的作業將 ETag 包含在 response 中傳回,且可透過 response['.metadata'].etag 擷取 ETag。This is returned as part of the response for any entity-related operation and can be retrieved through response['.metadata'].etag.

  2. 對實體執行更新操作時,請將先前擷取的 ETag 資訊新增至新的實體。When performing an update operation on an entity, add the ETag information previously retrieved to the new entity. 例如:For example:

    entity2['.metadata'].etag = currentEtag;entity2['.metadata'].etag = currentEtag;

  3. 執行更新操作。Perform the update operation. 如果在您擷取 ETag 值之後,實體已發生修改 (例如另一個應用程式執行個體),系統就會傳回 error,指出不符合要求中指定的更新條件。If the entity has been modified since you retrieved the ETag value, such as another instance of your application, an error is returned stating that the update condition specified in the request was not satisfied.

使用 replaceEntitymergeEntity 時,如果所要更新的實體不存在,更新作業就會失敗;因此,如果您想要不論實體是否已經存在都儲存該實體,請使用 insertOrReplaceEntityinsertOrMergeEntityWith replaceEntity and mergeEntity, if the entity that is being updated doesn't exist, then the update operation fails; therefore, if you want to store an entity regardless of whether it already exists, use insertOrReplaceEntity or insertOrMergeEntity.

成功的更新作業 result 會包含所更新實體的 EtagThe result for successful update operations contains the Etag of the updated entity.

使用實體群組Work with groups of entities

有時候批次提交多個操作是有意義的,可以確保伺服器會進行不可部分完成的處理。Sometimes it makes sense to submit multiple operations together in a batch to ensure atomic processing by the server. 若要達到此目的,請使用 TableBatch 類別建立批次,然後使用 executeBatchTableService 方法執行批次作業。To accomplish that, use the TableBatch class to create a batch, and then use the executeBatch method of TableService to perform the batched operations.

下列範例示範在批次中提交兩個實體:The following example demonstrates submitting two entities in a batch:

var task1 = {
  PartitionKey: {'_':'hometasks'},
  RowKey: {'_': '1'},
  description: {'_':'Take out the trash'},
  dueDate: {'_':new Date(2015, 6, 20)}
};
var task2 = {
  PartitionKey: {'_':'hometasks'},
  RowKey: {'_': '2'},
  description: {'_':'Wash the dishes'},
  dueDate: {'_':new Date(2015, 6, 20)}
};

var batch = new azure.TableBatch();

batch.insertEntity(task1, {echoContent: true});
batch.insertEntity(task2, {echoContent: true});

tableSvc.executeBatch('mytable', batch, function (error, result, response) {
  if(!error) {
    // Batch completed
  }
});

就成功的批次作業而言,result 會包含批次中每個作業的相關資訊。For successful batch operations, result contains information for each operation in the batch.

處理批次作業Work with batched operations

您可以檢視 operations 屬性來檢查新增至批次的作業。You can inspect operations added to a batch by viewing the operations property. 您也可以使用下列方法來處理操作:You can also use the following methods to work with operations:

  • clear - 從批次中清除所有作業。clear - Clears all operations from a batch.
  • getOperations - 從批次中取得作業。getOperations - Gets an operation from the batch.
  • hasOperations - 如果批次包含作業,便傳回 true。hasOperations - Returns true if the batch contains operations.
  • removeOperations - 移除作業。removeOperations - Removes an operation.
  • size - 傳回批次中的作業數目。size - Returns the number of operations in the batch.

依索引鍵擷取實體Retrieve an entity by key

若要根據 PartitionKeyRowKey 傳回特定的實體,請使用 retrieveEntity 方法。To return a specific entity based on the PartitionKey and RowKey, use the retrieveEntity method.

tableSvc.retrieveEntity('mytable', 'hometasks', '1', function(error, result, response){
  if(!error){
    // result contains the entity
  }
});

在此作業完成之後,result 就會包含實體。After this operation is complete, result contains the entity.

查詢實體集合Query a set of entities

若要查詢資料表,請透過 TableQuery 物件使用下列子句建置查詢運算式:To query a table, use the TableQuery object to build up a query expression using the following clauses:

  • select - 要從查詢傳回的欄位。select - The fields to be returned from the query.

  • where - where 子句。where - The where clause.

    • and - and where 條件。and - An and where condition.
    • or - or where 條件。or - An or where condition.
  • top - 要擷取的項目數目。top - The number of items to fetch.

下列範例建立的查詢會傳回 PartitionKey 為 'hometasks' 的前 5 個項目。The following example builds a query that returns the top five items with a PartitionKey of 'hometasks'.

var query = new azure.TableQuery()
  .top(5)
  .where('PartitionKey eq ?', 'hometasks');

由於沒有使用 select,因此會傳回所有欄位。Because select is not used, all fields are returned. 若要對資料表執行查詢,請使用 queryEntitiesTo perform the query against a table, use queryEntities. 下列範例使用此查詢從 'mytable' 傳回實體。The following example uses this query to return entities from 'mytable'.

tableSvc.queryEntities('mytable',query, null, function(error, result, response) {
  if(!error) {
    // query was successful
  }
});

如果作業成功,result.entries 就會包含符合查詢的實體陣列。If successful, result.entries contains an array of entities that match the query. 如果查詢無法傳回所有實體,result.continuationToken 便不是 Null,而可作為 queryEntities 的第三個參數來擷取更多結果。If the query was unable to return all entities, result.continuationToken is non-null and can be used as the third parameter of queryEntities to retrieve more results. 在初始查詢中,第三個參數請使用 nullFor the initial query, use null for the third parameter.

查詢實體屬性的子集Query a subset of entity properties

一項資料表查詢可以只擷取實體的少數欄位。A query to a table can retrieve just a few fields from an entity. 這可以減少頻寬並提高查詢效能 (尤其是對大型實體而言)。This reduces bandwidth and can improve query performance, especially for large entities. 請使用 select 子句,並傳遞要傳回的欄位名稱。Use the select clause and pass the names of the fields to return. 例如,下列查詢只會傳回 descriptiondueDate 欄位。For example, the following query returns only the description and dueDate fields.

var query = new azure.TableQuery()
  .select(['description', 'dueDate'])
  .top(5)
  .where('PartitionKey eq ?', 'hometasks');

刪除實體Delete an entity

您可以使用實體的資料分割和資料列索引鍵來刪除實體。You can delete an entity using its partition and row keys. 在此範例中,task1 物件包含要刪除之實體的 RowKeyPartitionKey 值。In this example, the task1 object contains the RowKey and PartitionKey values of the entity to delete. 然後物件會傳給 deleteEntity 方法。Then the object is passed to the deleteEntity method.

var task = {
  PartitionKey: {'_':'hometasks'},
  RowKey: {'_': '1'}
};

tableSvc.deleteEntity('mytable', task, function(error, response){
  if(!error) {
    // Entity deleted
  }
});

注意

刪除項目時應該考慮使用 ETag,以確保項目未被另一個程序修改過。Consider using ETags when deleting items, to ensure that the item hasn't been modified by another process. 請參閱 更新實體 ,以取得使用 ETag 的相關資訊。See Update an entity for information on using ETags.

刪除資料表Delete a table

下列程式碼會從儲存體帳戶刪除資料表。The following code deletes a table from a storage account.

tableSvc.deleteTable('mytable', function(error, response){
    if(!error){
        // Table deleted
    }
});

若不確定資料表是否存在,請使用 deleteTableIfExistsIf you are uncertain whether the table exists, use deleteTableIfExists.

使用接續 TokenUse continuation tokens

當您查詢大量結果的資料表時,請尋找接續 Token。When you are querying tables for large amounts of results, look for continuation tokens. 因為您的查詢可能會產生大量可用的資料,如果該查詢並非可識別接續權杖存在的查詢,可能會無法得知。There may be large amounts of data available for your query that you might not realize if you do not build to recognize when a continuation token is present.

當此類權杖存在時,在查詢實體期間傳回的 results 物件便會設定 continuationToken 屬性。The results object returned during querying entities sets a continuationToken property when such a token is present. 您可以在執行查詢使用此方法以繼續在分割和資料表實體之間移動。You can then use this when performing a query to continue to move across the partition and table entities.

查詢時,您可以在查詢物件執行個體與回呼函式之間提供一個 continuationToken 參數:When querying, you can provide a continuationToken parameter between the query object instance and the callback function:

var nextContinuationToken = null;
dc.table.queryEntities(tableName,
    query,
    nextContinuationToken,
    function (error, results) {
        if (error) throw error;

        // iterate through results.entries with results

        if (results.continuationToken) {
            nextContinuationToken = results.continuationToken;
        }

    });

如果您檢查 continuationToken 物件,您會找到像是 nextPartitionKeynextRowKeytargetLocation 的屬性,這些屬性可以用來逐一查看所有結果。If you inspect the continuationToken object, you will find properties such as nextPartitionKey, nextRowKey and targetLocation, which can be used to iterate through all the results.

您還可以使用 topcontinuationToken 來設定頁面大小。You can also use top along with continuationToken to set the page size.

使用共用存取簽章Work with shared access signatures

共用存取簽章 (SAS) 可安全地提供對資料表的細微存取權,而不必提供您的儲存體帳戶名稱或金鑰。Shared access signatures (SAS) are a secure way to provide granular access to tables without providing your Storage account name or keys. SAS 通常用來提供對資料的有限存取,例如允許行動應用程式查詢記錄。SAS are often used to provide limited access to your data, such as allowing a mobile app to query records.

信任的應用程式 (例如雲端型服務) 會使用 TableServicegenerateSharedAccessSignature 來產生 SAS,並提供它給不信任或不完全信任的應用程式 (例如行動應用程式)。A trusted application such as a cloud-based service generates a SAS using the generateSharedAccessSignature of the TableService, and provides it to an untrusted or semi-trusted application such as a mobile app. SAS 是使用原則來產生,該原則描述 SAS 有效期間的開始和結束日期,以及授與 SAS 持有者的存取等級。The SAS is generated using a policy, which describes the start and end dates during which the SAS is valid, as well as the access level granted to the SAS holder.

下列範例會產生新的共用存取原則,讓 SAS 持有者查詢 ('r') 資料表,並於建立它之後的 100 分鐘過期。The following example generates a new shared access policy that will allow the SAS holder to query ('r') the table, and expires 100 minutes after the time it is created.

var startDate = new Date();
var expiryDate = new Date(startDate);
expiryDate.setMinutes(startDate.getMinutes() + 100);
startDate.setMinutes(startDate.getMinutes() - 100);

var sharedAccessPolicy = {
  AccessPolicy: {
    Permissions: azure.TableUtilities.SharedAccessPermissions.QUERY,
    Start: startDate,
    Expiry: expiryDate
  },
};

var tableSAS = tableSvc.generateSharedAccessSignature('mytable', sharedAccessPolicy);
var host = tableSvc.host;

請注意,您必須一併提供主機資訊,因為當 SAS 持有者嘗試存取資料表時,會需要此資訊。Note that you must also provide the host information, as it is required when the SAS holder attempts to access the table.

用戶端應用程式接著以 TableServiceWithSAS 來使用 SAS,對資料表執行操作。The client application then uses the SAS with TableServiceWithSAS to perform operations against the table. 下列範例會連線到資料表並執行查詢。The following example connects to the table and performs a query. 如需關於資料表 SAS 的格式詳細資訊,請參閱使用共用存取簽章 (SAS) 對 Azure 儲存體資源授與有限存取權一文。See Grant limited access to Azure Storage resources using shared access signatures (SAS) article for the format of tableSAS.

// Note in the following command, host is in the format: `https://<your_storage_account_name>.table.core.windows.net` and the tableSAS is in the format: `sv=2018-03-28&si=saspolicy&tn=mytable&sig=9aCzs76n0E7y5BpEi2GvsSv433BZa22leDOZXX%2BXXIU%3D`;

var sharedTableService = azure.createTableServiceWithSas(host, tableSAS);
var query = azure.TableQuery()
  .where('PartitionKey eq ?', 'hometasks');

sharedTableService.queryEntities(query, null, function(error, result, response) {
  if(!error) {
    // result contains the entities
  }
});

由於產生的 SAS 只具有查詢權限,因此如果您嘗試插入、更新或刪除實體,就會傳回錯誤。Because the SAS was generated with only query access, an error is returned if you attempt to insert, update, or delete entities.

存取控制清單Access Control Lists

您也可以使用存取控制清單 (ACL) 來設定 SAS 的存取原則。You can also use an Access Control List (ACL) to set the access policy for a SAS. 如果您想要允許多個用戶端存取資料表,但對每個用戶端提供不同的存取原則,這便相當有用。This is useful if you want to allow multiple clients to access the table, but provide different access policies for each client.

ACL 是使用存取原則陣列來實作,每個原則有相關聯的識別碼。An ACL is implemented using an array of access policies, with an ID associated with each policy. 下列範例定義兩個原則,其中一個用於 'user1',另一個用於 'user2':The following example defines two policies, one for 'user1' and one for 'user2':

var sharedAccessPolicy = {
  user1: {
    Permissions: azure.TableUtilities.SharedAccessPermissions.QUERY,
    Start: startDate,
    Expiry: expiryDate
  },
  user2: {
    Permissions: azure.TableUtilities.SharedAccessPermissions.ADD,
    Start: startDate,
    Expiry: expiryDate
  }
};

下列範例會取得 hometasks 資料表的目前 ACL,然後使用 setTableAcl 來加入新的原則。The following example gets the current ACL for the hometasks table, and then adds the new policies using setTableAcl. 此方法允許:This approach allows:

var extend = require('extend');
tableSvc.getTableAcl('hometasks', function(error, result, response) {
if(!error){
    var newSignedIdentifiers = extend(true, result.signedIdentifiers, sharedAccessPolicy);
    tableSvc.setTableAcl('hometasks', newSignedIdentifiers, function(error, result, response){
      if(!error){
        // ACL set
      }
    });
  }
});

設定 ACL 之後,您便可以根據原則的識別碼來建立 SAS。After the ACL has been set, you can then create a SAS based on the ID for a policy. 下列範例會建立 'user2' 的新 SAS:The following example creates a new SAS for 'user2':

tableSAS = tableSvc.generateSharedAccessSignature('hometasks', { Id: 'user2' });

後續步驟Next steps

如需詳細資訊,請參閱下列資源。For more information, see the following resources.