Kelly Kelly - 2 months ago 7
Node.js Question

RabbitMQ and Node.js converting message buffer to JSON

I have a node.js app that connects to RabbitMQ to receive messages. When the messages come in and I output them to the console I get:
{ data: <Buffer 62 6c 61 68>, contentType: undefined }

How do I get a proper JSON or string out of this? Here is my example:

var amqp = require('amqp');

var connection = amqp.createConnection({ host: 'localhost' });

process.on('uncaughtException', function(err) {
console.error(err.stack);
});

connection.on('ready', function () {
// Use the default 'amq.topic' exchange
connection.queue('my-queue', function(q){
q.bind('#');

q.subscribe(function (message) {
console.log(message);
});
});
});


The messages are being sent using the RabbitMQ management console (for testing purposes currently). In this example I sent a simple message with the topic of "test" and the body "blah".

I'm new to Node.js but I have tried to do

console.log(message.toJSON());


and I get nothing. Not even an error message. (not sure how to catch the issue)

console.log(message.toString());


When I do this I get [object Object] which doesn't help

console.log(JSON.parse(message.toString('utf8')));


Also does nothing and I get no error message. I assuming it's failing but why I don't get an exception is unknown to me.

Answer

The answer was right in front of me. Leaving this up in case someone else has the same issue, but the solution was:

console.log(message.data.toString('utf8'));

I was getting the object and trying to convert it all and not the data property.

Comments