Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 767
Kelly Avatar asked Mar 17 '14 20:03

Kelly


People also ask

How will you convert a buffer to JSON in node JS?

To convert a Buffer to JSON , you can use the toJSON() method in the Buffer instance. // convert buff object to json const json = buff. toJSON();

How do I use RabbitMQ in node JS?

First, we have to ensure our queue is declared as durable . We can either do that in RabbitMQ admin console, or through code. Then we should ensure the messages in the queue are persistent by setting the persistent field as true . We will check both of them when we code.


2 Answers

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.

like image 40
Kelly Avatar answered Oct 01 '22 16:10

Kelly


If you are using amqplib then the below code solves the issue.

In the sender.js file i convert data to JSON string

var data = [{
   name: '********',
   company: 'JP Morgan',
   designation: 'Senior Application Engineer'
}];

ch.sendToQueue(q, Buffer.from(JSON.stringify(data)));

And in the receiver.js i use the below code to print the content from the queue. Here i parse the msg.content to JSON format.

ch.consume(q, function(msg) {
   console.log(" [x] Received");
   console.log(JSON.parse(msg.content));
}, {noAck: true});
like image 199
Libu Mathew Avatar answered Oct 01 '22 17:10

Libu Mathew