Azure SDK for JavaScript

Event Hubs Client Library

Connect to Azure Event Hubs with JavaScript

Easily send and receive events from Azure Event Hubs using the official Azure SDK for JavaScript.

What is Azure Event Hubs?

Azure Event Hubs is a highly scalable data streaming platform and event ingestion service. It can ingest and process millions of events per second. This client library provides a robust and efficient way to interact with Event Hubs from your JavaScript applications.

Key Features

🚀

High Throughput

Ingest and process millions of events per second with ease.

📦

Durable Storage

Events are durably stored, allowing for replayability and stream processing.

🔒

Secure Access

Leverage Azure Active Directory and Shared Access Signatures for secure authentication.

🧩

Partitioning

Distribute event streams across multiple partitions for parallel processing.

Getting Started

Let's get you up and running with the Event Hubs client library.

1. Installation

Install the package using npm or yarn:


npm install @azure/event-hubs
# or
yarn add @azure/event-hubs
            

2. Authentication

You'll need your Event Hubs connection string or Azure AD credentials. For simplicity, we'll use a connection string here.

3. Basic Producer Example

Here's a simple example to send events:

producer.ts

import { EventHubProducerClient } from "@azure/event-hubs";

            // Replace with your actual connection string and event hub name
            const connectionString = "YOUR_EVENT_HUBS_CONNECTION_STRING";
            const eventHubName = "YOUR_EVENT_HUB_NAME";

            async function main() {
                const producer = new EventHubProducerClient(connectionString, eventHubName);

                try {
                    console.log("Sending events...");
                    const batch = await producer.createBatch();
                    batch.tryAdd({ body: "Hello, Event Hubs!" });
                    batch.tryAdd({ body: "Another event." });
                    await producer.sendBatch(batch);
                    console.log("Events sent successfully.");
                } finally {
                    await producer.close();
                }
            }

            main().catch((err) => {
                console.error("Error sending events:", err);
            });
            

4. Basic Consumer Example

And here's how to receive events:

consumer.ts

import { EventHubConsumerClient, earliestEventPosition } from "@azure/event-hubs";

            // Replace with your actual connection string and event hub name
            const connectionString = "YOUR_EVENT_HUBS_CONNECTION_STRING";
            const eventHubName = "YOUR_EVENT_HUB_NAME";
            const consumerGroup = "$Default"; // Or your custom consumer group

            async function main() {
                const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);

                const subscription = consumerClient.subscribe({
                    async processEvents(events, context) {
                        console.log(`Received ${events.length} events:`);
                        for (const event of events) {
                            console.log(`  Partition: ${context.partitionId}, Offset: ${event.offset}, Sequence: ${event.sequenceNumber}`);
                            console.log(`  Body: ${event.body}`);
                        }
                    },
                    async processError(err, context) {
                        console.error(`Error in partition ${context.partitionId}: ${err.message}`);
                    }
                }, { startPosition: earliestEventPosition });

                console.log("Listening for events...");

                // Keep the process running to listen for events
                // In a real application, you would have a more sophisticated way to manage the subscription lifecycle
                await new Promise(resolve => setTimeout(resolve, 300000)); // Listen for 5 minutes

                await subscription.close();
                await consumerClient.close();
                console.log("Stopped listening.");
            }

            main().catch((err) => {
                console.error("Error receiving events:", err);
            });
            

Usage Examples

Explore common scenarios and advanced features:

Sending Events in Batches

The library allows you to create batches of events for efficient sending. The createBatch() method helps manage the size and composition of your batches.

Receiving Events with Different Start Positions

You can specify where to start reading events from a partition, such as earliestEventPosition, latestEventPosition, or a specific sequence number.

Managing Consumer Groups

Event Hubs uses consumer groups to allow multiple applications or different parts of the same application to read from an event hub independently.

Error Handling and Retries

The library includes built-in retry policies for transient network issues. You should also implement robust error handling in your application logic.

API Reference

Dive into the detailed API documentation for comprehensive information on classes, methods, and options.

View Full API Documentation