Apache Kafka is a robust, open-source distributed event streaming platform. It's widely used in distributed systems for building real-time data pipelines and streaming apps. If you're a JavaScript developer tinkering with Kafka, you're in the right place. Let's explore a hands-on example of producing and consuming messages with Kafka using Node.js.

Before diving into the code, ensure you have Kafka and Zookeeper installed and running locally or use Docker for a quick setup. Also, install the `kafkajs` library, which provides an easy-to-use client for Kafka in JavaScript: `npm install kafkajs`.

Producers in Kafka with JavaScript
Producers push data into Kafka topics. Let's create a simple Node.js application sending a message to the 'my-topic' topic.

First, import the required modules and set up an admin client to interact with Kafka:
```javascript const Kafka = require('kafkajs'); const kafka = new Kafka.Kafka({ clientId: 'my-app', brokers: ['localhost:9092'], }); const admin = kafka.admin(); ```
Creating a Kafka Topic

Before sending messages, create a topic:
```javascript await admin.createTopics({ topics: ['my-topic'], waitForAllTopicsToBeCreated: true, }); ```
Sending Messages
Now, produce a message using the `Kafka.Producer` class:

```javascript const producer = kafka.producer(); producer.connect(); await producer.send({ topic: 'my-topic', messages: [ { value: 'This is my first Kafka message!' }, ], }); producer.disconnect(); ```
Consumers in Kafka with JavaScript
Consumers fetch data from Kafka topics. Let's build a consumer that reads messages from the 'my-topic' topic we created.
First, set up a consumer client:

```javascript const consumer = kafka.consumer({ groupId: 'my-group' }); ```
Consuming Messages
Now, consume messages from the 'my-topic' topic:




















```javascript consumer.subscribe({ topic: 'my-topic', fromBeginning: true }); consumer.run({ eachMessage: async ({ topic, partition, message }) => { console.log({ value: message.value.toString() }); }}); ```
Handling Commitment
Consumers automatically commit offsets to Kafka for their group regularly. However, you might want to handle this manually in some scenarios:
```javascript consumer.run({ eachMessage: async ({ topic, partition, message }) => { await consumer.commit({ topic, partition, offsets: { [partition]: message.offset }, }); }}); ```
There you have it! A basic example of producing and consuming messages using Kafka with Node.js. Dive deeper into Kafka's features, such as using multiple brokers, handling failures, or processing streams with Kafka Streams API, to build robust, distributed data pipelines.