December 24, 2019
KafkaNodeJs
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.index.js
we will use kafkajs library.
npm install kafkajs
index.js
file and type below programconst { 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);