This guide will walk you through creating a simple JavaScript application to consume messages from an Azure Event Hub.
mkdir event-hub-consumer-js
cd event-hub-consumer-js
npm init -y
npm install @azure/event-hubs
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);
});
YOUR_EVENT_HUBS_CONNECTION_STRING and YOUR_EVENT_HUB_NAME in the consumer.js file with your actual Azure Event Hubs details.
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.
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.
To stop the consumer, simply press Ctrl+C in the terminal where the script is running.