Skip to content

Kafka in a Node.js process

Course: Kafka - chapter 4

Ref https://www.npmjs.com/package/kafkajs

  • Initialise project
npm init -y
npx tsc --init
  • Update package.json
"rootDir": "./src",
"outDir": "./dist"
  • Add src/index.ts
import { Kafka } from "kafkajs";
const kafka = new Kafka({
clientId: "my-app",
brokers: ["localhost:9092"]
})
const producer = kafka.producer();
const consumer = kafka.consumer({groupId: "my-app3"});
async function main() {
await producer.connect();
await producer.send({
topic: "quickstart-events",
messages: [{
value: "hi there"
}]
})
await consumer.connect();
await consumer.subscribe({
topic: "quickstart-events", fromBeginning: true
})
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
offset: message.offset,
value: message?.value?.toString(),
})
},
})
}
main();
  • Update package.json
"scripts": {
"start": "tsc -b && node dist/index.js"
},
  • Start the process
npm run start