Azure Event Hubs Quickstart

JavaScript Event Consumer

This guide will walk you through creating a simple JavaScript application to consume messages from an Azure Event Hub.

Prerequisites

Step 1: Set up your Project

1
Create a new directory for your project and navigate into it.

mkdir event-hub-consumer-js
cd event-hub-consumer-js
                
2
Initialize a Node.js project and install the necessary Azure Event Hubs SDK package.

npm init -y
npm install @azure/event-hubs
                

Step 2: Create the Consumer Script

Create a file named consumer.js and add the following code.


const { EventHubConsumerClient } = require("@azure/event-hubs");

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

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

    console.log("Starting event consumer...");

    const subscription = consumerClient.subscribe({
        async processEvents(events, context) {
            if (events.length === 0) {
                console.log("No new events");
                return;
            }

            console.log(`Received ${events.length} events:`);
            for (const event of events) {
                console.log(`  Offset: ${event.offset}, Sequence Number: ${event.sequenceNumber}`);
                console.log(`  Body: ${event.body}`);
                console.log(`  Properties: ${JSON.stringify(event.properties)}`);
            }
        },
        async processError(err, context) {
            console.error(`Error encountered: ${err.message}`);
        }
    });

    console.log("Event consumer started. Press Ctrl+C to stop.");

    // Keep the process running until interrupted
    process.on('SIGINT', async () => {
        console.log("Stopping event consumer...");
        await subscription.close();
        await consumerClient.close();
        console.log("Event consumer stopped.");
        process.exit();
    });
}

main().catch((err) => {
    console.error("Error running the consumer:", err);
    process.exit(1);
});
        
Tip: For security, consider using environment variables or Azure Key Vault to store your connection string instead of hardcoding it.

Step 3: Run the Consumer

1
Replace YOUR_EVENT_HUBS_CONNECTION_STRING and YOUR_EVENT_HUB_NAME in the consumer.js file with your actual Azure Event Hubs details.
2
Run the script using Node.js:

node consumer.js
                

The script will now connect to your Event Hub and start listening for incoming messages. You should see output indicating that the consumer has started. Any messages sent to your Event Hub will be logged to the console.

Step 4: Sending Test Messages (Optional)

To test the consumer, you can send messages to your Event Hub using another script, the Azure portal, or a tool like Azure CLI.

Once messages are sent, you should see them appear in the console output of your running consumer.js script.

Stopping the Consumer

To stop the consumer, simply press Ctrl+C in the terminal where the script is running.

Next Steps