Aftab
Aftab

Reputation: 2963

NodeJS kafka producer using kafkaJS library not working

I'm writting a kafka producer in NodeJS using kafkaJS library.

Below is my sample code. It makes connection with the kafka broker and sends message to a kafka topic "topic-name".

KafkaJS-Producer.js

const { Kafka } = require('kafkajs')

const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['localhost:9092']
})

const producer = kafka.producer() 

async () => {
  await producer.connect()
  await producer.send({
    topic: 'topic-name',
    messages: [
      { key: 'key1', value: 'hello world' },
      { key: 'key2', value: 'hey hey!' }
    ],
  })
  await producer.disconnect()
}

I ran the code with no error.

node SampleProducer.js

Consuming messages from topic as below:

kafka-console-consumer --bootstrap-server localhost:9092 --topic topic-name --from-beginning

But, I could not see any message being delivered to Kafka Topic.

What can be the reason for this?

Note:

Kafka is running on localhost. Topic is also created.

Resources:

https://www.npmjs.com/package/kafkajs https://kafka.apache.org/

Upvotes: 0

Views: 7544

Answers (1)

Aftab
Aftab

Reputation: 2963

Issue Resolved:

Actually, the issue was that the arrow function which was producing messages was not invoked. I made some changes to the code and it is working fine now:

var sendMessage = async () => {
  await producer.connect()
  await producer.send({
    topic: 'topic-name',
    messages: [
      { key: 'key1', value: 'hello world' },
      { key: 'key2', value: 'hey hey!' }
    ],
  })
  await producer.disconnect()
}

sendMessage();

Upvotes: 2

Related Questions