如何从node.js检查RabbitMQ中是否存在交换?

我想从node.js检查一个特定的RabbitMQ交换是否存在。 我正在使用Mocha作为testing框架。 我写了相同的代码,但我的期望似乎是不正确的。 如果没有交换,我希望交换variables具有未定义的值,但事实并非如此。 我正在使用amqp模块与RabbitMQ进行交互。 以下是代码:

var should = require('should'); var amqp = require('amqp'); //Configuration var amqpConnectionDetails = { 'host':'localhost', 'port':5672, 'login':'guest', 'password':'guest' }; describe('AMQP Objects', function(){ describe('Exchanges', function(){ it('There should exist an exchange', function(done){ var amqpConnection = amqp.createConnection(amqpConnectionDetails); amqpConnection.on('ready', function(){ var exchange = amqpConnection.exchange('some_exchange', {'passive':true, 'noDeclare':true}); exchange.should.not.be.equal(undefined); exchange.should.not.be.equal(null); done(); }); }); }); }); 

什么是检查交换存在的正确方法?

谢谢。

如果交换不存在,将会抛出一个错误(“Uncaught Error:NOT_FOUND – no exchange'some_exchange'in vhost'/'”)。 这意味着你应该添加一个“on error”方法来交换,以便捕获交换不存在时会抛出的错误。

其次,你应该从你的选项中删除“noDeclare”:true。

以下应该工作(如果交换不存在,它将优雅地退出,并且如果交换确实存在,将抛出exception):

 var amqp = require('amqp'); //Configuration var amqpConnectionDetails = { 'host':'localhost', 'port':5672, 'login':'guest', 'password':'guest' }; describe('AMQP Objects', function(){ describe('Exchanges', function(){ it('There should not exist an exchange', function(done){ var amqpConnection = amqp.createConnection(amqpConnectionDetails); amqpConnection.on('ready', function(){ var exchange = amqpConnection.exchange('some_exchange', {'passive':true}); exchange.on('error', function(error) { done(); }); exchange.on('open', function(exchange) { throw("exchange exists!") done(); }); }); }); }); });