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.
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();
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.
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With