-
Create a folder
KafkaNodeJs
-
Run
npm init
command from inside the folder and answer the few question like author, license, etc… once done, package.json file will be created in our folder. -
create a new file
index.js
we will use kafkajs library.
-
open command prompt and run
npm install kafkajs
-
open
index.js
file and type below program
const { Kafka, PartitionAssigners: { roundRobin } } = require("kafkajs");
const kafka = new Kafka({
clientId: 'my-app',
brokers: ["localhost:9092"]
});
const consumer = kafka.consumer({ groupId: "test-consumer-group-1", partitionAssigners: [roundRobin] });
const run = async () => {
// Consuming
await consumer.connect();
await consumer.subscribe({ topic: "testTopic", fromBeginning: false });
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log(message.value.toString() + " - from Partition " + partition);
}
});
};
run().catch(console.error);