{"name":"amqplib","version":"1.0.2","keywords":["AMQP","AMQP 0-9-1","RabbitMQ"],"author":{"name":"Michael Bridgen","email":"mikeb@squaremobius.net"},"license":"MIT","_id":"amqplib@1.0.2","maintainers":[{"name":"squaremo","email":"mikeb@squaremobius.net"},{"name":"cressie176","email":"stephen.cresswell@gmail.com"}],"homepage":"http://amqp-node.github.io/amqplib/","bugs":{"url":"https://github.com/amqp-node/amqplib/issues"},"dist":{"shasum":"67cff98162b5e6c42c44548b1b23747dcc34fa00","tarball":"http://registry-npm.ywwl.com/amqplib/download/amqplib-1.0.2.tgz","fileCount":84,"integrity":"sha512-QFzavIs3FxXA9/PWOiY/j5Arr7KFT0b1TYYsq9f5PyZ3Dv5H5hQXTK3fZTUUzzOo2BF1o/Vk5bHAKzlL40LfDA==","signatures":[{"sig":"MEUCIQD/AuI6GjggcVXYFL42olP3hFFDK8AI3z1RlKDWdl2wYQIgHXYLK3NAkill10TZuthGTxR21CyebSNIW7+2U36pIKk=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":467824,"size":88594,"noattachment":false,"key":"/amqplib/-/amqplib-1.0.2.tgz"},"main":"./channel_api.js","engines":{"node":">=18"},"gitHead":"b2cfaa2f635c84a4ec2e183a04764b7632fdf290","scripts":{"lint":"biome lint --max-diagnostics=1000 .","test":"make test","format":"biome format . --write","test:only":"node --test --test-only"},"_npmUser":{"name":"cressie176","email":"stephen.cresswell@gmail.com"},"repository":{"url":"git+https://github.com/amqp-node/amqplib.git","type":"git"},"_npmVersion":"11.11.1","description":"An AMQP 0-9-1 (e.g., RabbitMQ) library and client.","directories":{},"_nodeVersion":"25.8.2","dependencies":{"buffer-more-ints":"~1.0.0"},"_hasShrinkwrap":false,"devDependencies":{"claire":"0.4.1","lefthook":"^1.12.3","uglify-js":"2.8.x","@biomejs/biome":"^2.2.2"},"_npmOperationalInternal":{"tmp":"tmp/amqplib_1.0.2_1774730020235_0.5879269780422569","host":"s3://npm-registry-packages-npm-production"},"readme":"# AMQP 0-9-1 library and client for Node.JS\n\n[![NPM version](https://img.shields.io/npm/v/amqplib.svg?style=flat-square)](https://www.npmjs.com/package/amqplib)\n[![NPM downloads](https://img.shields.io/npm/dm/amqplib.svg?style=flat-square)](https://www.npmjs.com/package/amqplib)\n[![Node.js CI](https://github.com/amqp-node/amqplib/workflows/Node.js%20CI/badge.svg)](https://github.com/amqp-node/amqplib/actions?query=workflow%3A%22Node.js+CI%22)\n[![amqplib](https://snyk.io/advisor/npm-package/amqplib/badge.svg)](https://snyk.io/advisor/npm-package/amqplib)\n\nA library for making AMQP 0-9-1 clients for Node.JS, and an AMQP 0-9-1 client for Node.JS v18+. This library does not implement [AMQP1.0](https://github.com/amqp-node/amqplib/issues/63) or [AMQP0-10](https://github.com/amqp-node/amqplib/issues/94).\n\n    npm install amqplib\n\n## RabbitMQ Compatibility\n\nOnly `0.10.7` and later versions of this library are compatible with RabbitMQ 4.1.0 (and later releases).\n\n## Links\n * [Change log][changelog]\n * [GitHub pages][gh-pages]\n * [API reference][gh-pages-apiref]\n * [Troubleshooting][gh-pages-trouble]\n * [Examples from RabbitMQ tutorials][tutes]\n\n## Project status\n\n - Expected to work\n - Complete high-level and low-level APIs (i.e., all bits of the protocol)\n - Stable APIs\n - A fair few tests\n - Measured test coverage\n - Ports of the [RabbitMQ tutorials][rabbitmq-tutes] as [examples][tutes]\n - Used in production\n\nStill working on:\n\n - Getting to 100% (or very close to 100%) test coverage\n\n## Callback API example\n\n```javascript\nconst amqplib = require('amqplib/callback_api');\nconst queue = 'tasks';\n\namqplib.connect('amqp://localhost', (err, conn) => {\n  if (err) throw err;\n\n  conn.on('error', (err) => { console.error('Connection error:', err); });\n  conn.on('handler-error', (err, event) => { console.error(`Uncaught exception in connection ${event} listener:`, err); });\n\n  // Listener\n  conn.createChannel((err, ch2) => {\n    if (err) throw err;\n\n    ch2.on('error', (err) => { console.error('Channel error:', err); });\n    ch2.on('handler-error', (err, event) => { console.error(`Uncaught exception in channel ${event} listener:`, err); });\n\n    ch2.assertQueue(queue);\n\n    ch2.consume(queue, (msg) => {\n      if (msg !== null) {\n        console.log(msg.content.toString());\n        ch2.ack(msg);\n      } else {\n        console.log('Consumer cancelled by server');\n      }\n    });\n  });\n\n  // Sender\n  conn.createChannel((err, ch1) => {\n    if (err) throw err;\n\n    ch1.on('error', (err) => { console.error('Channel error:', err); });\n    ch1.on('handler-error', (err, event) => { console.error(`Uncaught exception in channel ${event} listener:`, err); });\n    ch1.assertQueue(queue);\n\n    setInterval(() => {\n      ch1.sendToQueue(queue, Buffer.from('something to do'));\n    }, 1000);\n  });\n});\n```\n\n## Promise/Async API example\n\n```javascript\nconst amqplib = require('amqplib');\n\n(async () => {\n  const queue = 'tasks';\n  const conn = await amqplib.connect('amqp://localhost');\n  conn.on('error', (err) => { console.error('Connection error:', err); });\n  conn.on('handler-error', (err, event) => { console.error(`Uncaught exception in connection ${event} listener:`, err); });\n\n  const ch1 = await conn.createChannel();\n  ch1.on('error', (err) => { console.error('Channel error:', err); });\n  ch1.on('handler-error', (err, event) => { console.error(`Uncaught exception in channel ${event} listener:`, err); });\n  await ch1.assertQueue(queue);\n\n  // Listener\n  ch1.consume(queue, (msg) => {\n    if (msg !== null) {\n      console.log('Received:', msg.content.toString());\n      ch1.ack(msg);\n    } else {\n      console.log('Consumer cancelled by server');\n    }\n  });\n\n  // Sender\n  const ch2 = await conn.createChannel();\n  ch2.on('error', (err) => { console.error('Channel error:', err); });\n  ch2.on('handler-error', (err, event) => { console.error(`Uncaught exception in channel ${event} listener:`, err); });\n\n  setInterval(() => {\n    ch2.sendToQueue(queue, Buffer.from('something to do'));\n  }, 1000);\n})();\n\n```\n\n## Opt-in recovery\n\nAutomatic recovery is available as an opt-in feature through `connect` options:\n\n```javascript\nconst amqplib = require('amqplib');\n\nconst connection = await amqplib.connect('amqp://localhost', {\n  recovery: {\n    initialDelay: 200, // ms\n    maxDelay: 5000, // ms\n    factor: 2,\n    jitter: 0.2,\n    maxRetries: Infinity,\n    async setup(model) {\n      // Called after every successful (re)connect.\n      // Recreate topology/consumers here.\n      const ch = await model.createChannel();\n      await ch.assertQueue('tasks', {durable: true});\n    },\n  },\n});\n\nconnection.on('connect', () => {\n  console.log('connected');\n});\n\nconnection.on('disconnect', (err) => {\n  console.warn('disconnected', err.message);\n});\n```\n\nCallback API supports the same option:\n\n```javascript\nconst amqplib = require('amqplib/callback_api');\n\namqplib.connect(\n  'amqp://localhost',\n  {\n    recovery: {\n      initialDelay: 200,\n      maxDelay: 5000,\n      setup(model, done) {\n        model.createChannel((err, ch) => {\n          if (err) return done(err);\n          ch.assertQueue('tasks', {durable: true}, done);\n        });\n      },\n    },\n  },\n  (err, conn) => {\n    if (err) throw err;\n    conn.on('connect', () => console.log('connected'));\n  },\n);\n```\n\nWithout `recovery` options, behavior is unchanged.\n\n### Attaching listeners before the first connection\n\nBy default `connect` waits for the first successful connection before\nresolving (or invoking the callback), so events emitted during the initial\nattempt such as `connect-failed` and `reconnect-scheduled` cannot be observed.\nSet `waitForConnect: false` to get the connection handle immediately. You can\nthen attach listeners, call `waitForConnect()` to await the first connection,\nor call `close()` to cancel the initial attempt. Channel operations wait for a\nconnection internally, so `createChannel()` can be called straight away.\n\n```javascript\nconst connection = await amqplib.connect('amqp://localhost', {\n  recovery: { waitForConnect: false },\n});\n\nconnection.on('connect-failed', (err) => {\n  console.warn('connection attempt failed', err.message);\n});\n\nconnection.on('reconnect-scheduled', ({ attempt, delay }) => {\n  console.log(`retrying (attempt ${attempt}) in ${delay}ms`);\n});\n\nawait connection.waitForConnect();\n```\n\nThe callback API returns the connection handle synchronously, so listeners can\nalways be attached before the first attempt. With `waitForConnect: false` the\ncallback is invoked immediately with the handle instead of after the first\nconnection, and `waitForConnect(callback)` can be used to be notified once\nconnected.\n\n### Custom delay strategy\n\nBy default, reconnect delays follow an exponential backoff with jitter,\ncontrolled by `initialDelay`, `maxDelay`, `factor` and `jitter`. To use a\ndifferent strategy entirely (full jitter, decorrelated jitter, a fixed step\nschedule, etc.), provide a `calculateDelay` function instead:\n\n```javascript\nconst connection = await amqplib.connect('amqp://localhost', {\n  recovery: {\n    maxRetries: Infinity,\n    // Called with the reconnect attempt number, starting at 1.\n    // Must return the delay in milliseconds.\n    calculateDelay(attempt) {\n      return Math.min(30000, 100 * 2 ** (attempt - 1));\n    },\n  },\n});\n```\n\n`maxDelay` only bounds the built-in strategy. Once you provide `calculateDelay`,\namqplib does not cap its return value - you're responsible for enforcing your\nown maximum, as the example above does with `Math.min`.\n\nWhen `calculateDelay` is absent, the built-in strategy is used. If it throws,\nor returns something other than a finite, non-negative number, amqplib does\nnot fall back to the built-in strategy. Instead recovery gives up as if\n`maxRetries` had been exhausted: the initial `connect` rejects (or the\ncallback receives the error), pending channel operations reject, and\n`reconnect-failed` is emitted with the error. A broken `calculateDelay` is a\nbug in caller-supplied code, so it is surfaced rather than papered over.\n\n### Separate retry budget for the initial connection\n\nBy default `maxRetries` bounds every phase of recovery, including the attempts\nmade before the first connection succeeds. To give the very first connection\nits own budget, set `initialMaxRetries`; once connected, `maxRetries` applies.\nA common production posture is to fail fast at startup, so a misconfigured or\nunreachable broker fails the deployment, while never giving up on a service\nthat has already connected:\n\n```javascript\nconst connection = await amqplib.connect('amqp://localhost', {\n  recovery: {\n    initialMaxRetries: 5, // give up (and reject connect) after 5 failed retries at startup\n    maxRetries: Infinity, // but keep reconnecting forever once connected\n  },\n});\n```\n\nWhen the initial budget is exhausted `connect` rejects (or the callback receives\nthe error) and `reconnect-failed` is emitted. `initialMaxRetries` defaults to\n`maxRetries`, so behaviour is unchanged unless it is set.\n\n## Error handling in event handlers\n\nIf a user-supplied event handler throws a synchronous error, the throw will\npropagate into amqplib internals. Depending on where in the call stack it\nescapes, this can silently swallow the error, or close the channel or\nconnection.\n\nTo avoid this, register a `handler-error` listener on the connection and on\neach channel. If a listener is present, amqplib will catch any throw from a\nuser event handler and deliver it there instead of letting it propagate\ninternally. The listener receives the thrown error and the name of the event\nwhose handler threw.\n\nNote that `handler-error` is not a replacement for the `error` event.\nThe `error` event is emitted by amqplib itself when the connection or channel\nencounters a protocol-level error. The `handler-error` event is only emitted\nwhen *your own* event listener throws.\n\n```js\nconst connection = await amqp.connect('amqp://localhost');\n\nconnection.on('error', (err) => { /* handle protocol errors */ });\nconnection.on('handler-error', (err, event) => {\n  console.error(`Uncaught exception in connection ${event} listener:`, err);\n});\n\nconst channel = await connection.createChannel();\n\nchannel.on('error', (err) => { /* handle protocol errors */ });\nchannel.on('handler-error', (err, event) => {\n  console.error(`Uncaught exception in channel ${event} listener:`, err);\n});\n```\n\nIf no `handler-error` listener is registered, behaviour is unchanged from\nprevious versions.\n\n## Running tests\n\n    npm test\n\nTo run the tests RabbitMQ is required. Either install it with your package\nmanager, or use [docker][] to run a RabbitMQ instance.\n\n    docker run -d --name amqp.test -p 5672:5672 rabbitmq\n\nIf prefer not to run RabbitMQ locally it is also possible to use a\ninstance of RabbitMQ hosted elsewhere. Use the `URL` environment\nvariable to configure a different amqp host to connect to. You may\nalso need to do this if docker is not on localhost; e.g., if it's\nrunning in docker-machine.\n\nOne public host is dev.rabbitmq.com:\n\n    URL=amqp://dev.rabbitmq.com npm test\n\n**NB** You may experience test failures due to timeouts if using the\ndev.rabbitmq.com instance.\n\nYou can run it under different versions of Node.JS using [nave][]:\n\n    nave use 10 npm test\n\nor run the tests on all supported versions of Node.JS in one go:\n\n    make test-all-nodejs\n\n(which also needs `nave` installed, of course).\n\nLastly, setting the environment variable `LOG_ERRORS` will cause the\ntests to output error messages encountered, to the console; this is\nreally only useful for checking the kind and formatting of the errors.\n\n    LOG_ERRORS=true npm test\n\n## Test coverage\n\n    make coverage\n    open file://`pwd`/coverage/lcov-report/index.html\n\n[gh-pages]: https://amqp-node.github.io/amqplib/\n[gh-pages-apiref]: https://amqp-node.github.io/amqplib/channel_api.html\n[gh-pages-trouble]: https://amqp-node.github.io/amqplib/#troubleshooting\n[nave]: https://github.com/isaacs/nave\n[tutes]: https://github.com/amqp-node/amqplib/tree/main/examples/tutorials\n[rabbitmq-tutes]: http://www.rabbitmq.com/getstarted.html\n[changelog]: https://github.com/amqp-node/amqplib/blob/main/CHANGELOG.md\n[docker]: https://www.docker.com/\n","publish_time":1774730020399,"_cnpm_publish_time":1774730020399,"dist-tags":{"latest":"2.2.1"}}