Azure Tables SDK for JavaScript

The Azure Tables client library for JavaScript allows you to interact with Azure Table Storage, a NoSQL datastore that can accept unsecured, cross-site access. Use Azure Tables to store large amounts of structured, non-relational data. You can find table data across different access tiers, from frequently accessed to infrequently accessed, and archive data that is rarely accessed.

Tip: This documentation covers the latest stable version of the Azure Tables SDK for JavaScript.

Getting Started

Before you begin, ensure you have an Azure subscription and a storage account. You can create these resources in the Azure portal.

Installation

Install the Azure Tables client library for JavaScript using npm:

npm install @azure/data-tables

Authentication

You can authenticate to Azure Table Storage in several ways:

Using Connection String

// Import necessary classes
import { TableServiceClient } from "@azure/data-tables";

// Replace with your actual connection string
const connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";

// Create a TableServiceClient
const tableServiceClient = TableServiceClient.fromConnectionString(connectionString);

Using Shared Key Credential

import { TableServiceClient, StorageSharedKeyCredential } from "@azure/data-tables";

// Replace with your actual account name and key
const accountName = "YOUR_STORAGE_ACCOUNT_NAME";
const accountKey = "YOUR_STORAGE_ACCOUNT_KEY";

const sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);
const tableServiceClient = new TableServiceClient(
    `https://${accountName}.table.core.windows.net`,
    sharedKeyCredential
);

Using Azure Identity

Ensure you have installed the Azure Identity library: npm install @azure/identity

import { TableServiceClient } from "@azure/data-tables";
import { DefaultAzureCredential } from "@azure/identity";

// Replace with your storage account name
const accountName = "YOUR_STORAGE_ACCOUNT_NAME";

// Authenticate using DefaultAzureCredential
const credential = new DefaultAzureCredential();

const tableServiceClient = new TableServiceClient(
    `https://${accountName}.table.core.windows.net`,
    credential
);

Core Concepts

Azure Table Storage is a NoSQL key-value store that allows you to store and query a massive amount of data. The fundamental components are:

Working with Tables

The TableServiceClient object is the entry point for interacting with Azure Table Storage.

Creating a Table

You can create a new table using the createTable method.

async function createMyTable() {
    const tableName = "mySampleTable";
    try {
        const createResponse = await tableServiceClient.createTable(tableName);
        console.log(`Table created: ${tableName}`, createResponse);
    } catch (error) {
        console.error("Error creating table:", error);
    }
}

// Call the function to create the table
// createMyTable();

Listing Tables

Retrieve a list of all tables in your storage account.

async function listMyTables() {
    try {
        const iter = tableServiceClient.listTables();
        let results = | [];
        for_await (const table of iter) {
            results = | [...results, table.tableName];
        }
        console.log("Tables:", results);
    } catch (error) {
        console.error("Error listing tables:", error);
    }
}

// Call the function to list tables
// listMyTables();

Deleting a Table

Remove a table and all its data.

async function deleteMyTable() {
    const tableName = "mySampleTable"; // Replace with your table name
    try {
        const deleteResponse = await tableServiceClient.deleteTable(tableName);
        console.log(`Table deleted: ${tableName}`, deleteResponse);
    } catch (error) {
        console.error("Error deleting table:", error);
    }
}

// Call the function to delete the table
// deleteMyTable();

Working with Entities

Use the TableClient to perform operations on entities within a specific table.

Creating a TableClient

import { TableClient } from "@azure/data-tables";

// Replace with your table name and connection string
const tableName = "mySampleTable";
const connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";

const tableClient = TableClient.fromConnectionString(connectionString, tableName);

Inserting an Entity

Entities are represented as JavaScript objects with properties. You must include partitionKey and rowKey.

async function insertMyEntity() {
    const entity = {
        partitionKey: "Users",
        rowKey: "user123",
        email: "user123@example.com",
        displayName: "Alice Smith",
        age: 30
    };

    try {
        const insertResponse = await tableClient.createEntity(entity);
        console.log("Entity inserted successfully:", insertResponse);
    } catch (error) {
        console.error("Error inserting entity:", error);
    }
}

// Call the function to insert an entity
// insertMyEntity();

Getting an Entity

Retrieve a single entity by its partition key and row key.

async function getMyEntity() {
    const partitionKey = "Users";
    const rowKey = "user123";

    try {
        const entity = await tableClient.getEntity(partitionKey, rowKey);
        console.log("Retrieved entity:", entity);
    } catch (error) {
        console.error("Error getting entity:", error);
    }
}

// Call the function to get an entity
// getMyEntity();

Querying Entities

Query entities using OData filters for more advanced retrieval.

async function queryMyEntities() {
    // Query for all entities with partitionKey "Users" and age greater than 25
    const queryOptions = {
        filter: "PartitionKey eq 'Users' and age gt 25"
    };

    try {
        const iter = tableClient.listEntities(queryOptions);
        let entities = | [];
        for_await (const entity of iter) {
            entities = | [...entities, entity];
        }
        console.log("Queried entities:", entities);
    } catch (error) {
        console.error("Error querying entities:", error);
    }
}

// Call the function to query entities
// queryMyEntities();

Updating an Entity

Update an existing entity. If the entity doesn't exist, it will be created (upsert).

async function updateMyEntity() {
    const entity = {
        partitionKey: "Users",
        rowKey: "user123",
        displayName: "Alice Wonderland", // Updated name
        age: 31, // Updated age
        status: "Active" // New property
    };

    try {
        const updateResponse = await tableClient.upsertEntity(entity, "Merge"); // "Merge" updates existing properties, "Replace" overwrites
        console.log("Entity updated successfully:", updateResponse);
    } catch (error) {
        console.error("Error updating entity:", error);
    }
}

// Call the function to update an entity
// updateMyEntity();

Deleting an Entity

Remove an entity by its partition key and row key.

async function deleteMyEntity() {
    const partitionKey = "Users";
    const rowKey = "user123";

    try {
        const deleteResponse = await tableClient.deleteEntity(partitionKey, rowKey);
        console.log(`Entity deleted: PartitionKey='${partitionKey}', RowKey='${rowKey}'`, deleteResponse);
    } catch (error) {
        console.error("Error deleting entity:", error);
    }
}

// Call the function to delete an entity
// deleteMyEntity();

API Reference

The Azure Tables SDK for JavaScript provides a comprehensive set of methods for managing your table data.

TableServiceClient

Methods for managing tables:

Method Description
createTable(tableName: string) Creates a new table.
deleteTable(tableName: string) Deletes a table.
listTables() Lists all tables in the storage account.
getTableClient(tableName: string) Returns a TableClient for the specified table.

TableClient

Methods for managing entities within a table:

Method Description
createEntity(entity: object) Inserts a new entity.
getEntity(partitionKey: string, rowKey: string) Retrieves a single entity.
listEntities(options?: EntityListOptions) Lists entities in the table, supporting OData filters.
upsertEntity(entity: object, mode?: "Merge" | "Replace") Inserts or updates an entity.
updateEntity(entity: object, mode?: "Merge" | "Replace") Updates an existing entity.
deleteEntity(partitionKey: string, rowKey: string) Deletes an entity.
submitTransaction(entities: object[]) Submits a batch of operations as a transaction.

Further Reading