1. Node.js
  2. Tutorial

Build Producer

Let's create the JavaScript producer application by pasting the following code into a file producer.js.

const { Kafka } = require('kafkajs')

const kafka = new Kafka({
  // User-specific properties that you must set
  clientId: 'my-app',
  brokers: ['<BOOTSTRAP SERVERS>'],

  // Fixed properties
  ssl: true,
  sasl: {
    mechanism: 'plain',
    username: 'unused',
    password: 'token:<API KEY>',
  },
})

async function send() {
  let topic = 'purchases'

  let users = ['eabara', 'jsmith', 'sgarcia', 'jbernard', 'htanaka', 'awalther']
  let items = ['book', 'alarm clock', 't-shirts', 'gift card', 'batteries']

  const producer = kafka.producer({})
  await producer.connect()

  let numEvents = 10
  for (let idx = 0; idx < numEvents; ++idx) {
    const key = users[Math.floor(Math.random() * users.length)]
    const value = Buffer.from(items[Math.floor(Math.random() * items.length)])

    let resp = await producer.send({
      topic: topic,
      messages: [{ key: key, value: value }],
    })
    let k = key.toString().padEnd(10, ' ')
    console.log(`Produced event to topic ${topic}: key = ${k} value = ${value}`)
  }

  await producer.disconnect()
}

send().catch((err) => {
  console.error(`Something went wrong:\n${err}`)
  process.exit(1)
})

Fill in the appropriate <BOOTSTRAP SERVERS> endpoint and <API KEY> in the brokers and sasl.password properties where the client configuration object is created.

Previous
Create Topic