AMQP 0-9-1 Client for Node.js

1.0.3 · active · verified Tue Apr 21

amqplib is a robust and widely-used library for building AMQP 0-9-1 clients in Node.js, specifically designed for interaction with brokers like RabbitMQ. Currently stable at version 1.0.3, it offers both a traditional callback-based API and a modern Promise/async-await API, catering to diverse asynchronous programming styles. The library generally maintains a consistent release cadence, incorporating updates and compatibility fixes. A key differentiator is its comprehensive implementation of the AMQP 0-9-1 protocol, covering both high-level and low-level functionalities, ensuring full control over message queuing operations. It explicitly does not support AMQP 1.0 or AMQP 0-10, focusing solely on the 0-9-1 specification. It is actively maintained, stable, and used in production environments, with ongoing efforts to improve test coverage and performance. Its minimal dependencies make it a lean choice for AMQP communication.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to RabbitMQ, setting up a queue, and both publishing and consuming messages using the modern Promise/Async API.

import { connect } from 'amqplib';

(async () => {
  const queue = 'tasks';
  let connection;
  try {
    connection = await connect('amqp://localhost');
    const channel = await connection.createChannel();
    await channel.assertQueue(queue, { durable: false });

    // Listener (Consumer)
    channel.consume(queue, (msg) => {
      if (msg !== null) {
        console.log('Received message:', msg.content.toString());
        channel.ack(msg);
      } else {
        console.log('Consumer cancelled by server');
      }
    }, { noAck: false });

    console.log('Waiting for messages in %s. To exit press CTRL+C', queue);

    // Sender (Producer)
    const senderChannel = await connection.createChannel();
    setInterval(() => {
      const message = `Task update: ${new Date().toISOString()}`;
      senderChannel.sendToQueue(queue, Buffer.from(message));
      console.log('Sent:', message);
    }, 2000);

  } catch (error) {
    console.error('Failed to connect to RabbitMQ or perform operations:', error);
    if (connection) {
      await connection.close();
    }
    process.exit(1);
  }
})();

view raw JSON →