kafka-pub-sub
Version:
Enterprise-grade Kafka publish/subscribe library for Node.js — producer pool, batch sending, DLQ, SSL/SASL, multi-broker, and real-world industry examples.
49 lines (38 loc) • 1.29 kB
JavaScript
/**
* QUICKSTART — Publisher
*
* Run subscribe.js in Terminal 1 first, then run this in Terminal 2.
*
* Usage:
* node examples/quickstart/publish.js
* node examples/quickstart/publish.js 5 ← send 5 messages
*/
require('dotenv').config({ path: require('path').resolve(__dirname, '../../.env') });
const { ProduceEvent } = require('../../index');
async function main() {
const count = parseInt(process.argv[2] || '3', 10);
console.log(`Publishing ${count} message(s) to "quickstart.topic"...\n`);
for (let i = 1; i <= count; i++) {
const data = {
messageNumber: i,
text: `Hello from message #${i}`,
sentAt: new Date().toISOString(),
};
await ProduceEvent(
'quickstart.topic',
'QUICKSTART_EVENT',
data,
{ 'x-source': 'quickstart-publisher' },
{ correlationId: `msg-${i}` }
);
console.log(`✓ Sent message #${i}:`, JSON.stringify(data));
// Small delay between messages so you can watch them arrive one by one
if (i < count) await new Promise((r) => setTimeout(r, 500));
}
await ProduceEvent.disconnect();
console.log('\nDone. Check Terminal 1 to see the messages arrive.');
}
main().catch((err) => {
console.error('Publisher error:', err.message);
process.exit(1);
});