RabbitMQ and Node.js converting message buffer to JSON

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

How do I get the correct JSON or string from 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);
        });
    });
});

Messages are sent using the RabbitMQ management console (currently for testing purposes). In this example, I sent a simple message with the subject "test" and the body "blah".

I am new to node.js but I tried to do

console.log(message.toJSON());

and I get nothing. Even an error message. (not sure how to catch the problem)

console.log(message.toString());

When I do this, I get [object Object], which does not help

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

, . , , , .

+5
3

. , - ​​ , :

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

, .

+9

amqplib, .

sender.js JSON

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

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

receiver.js . msg.content JSON.

ch.consume(q, function(msg) {
   console.log(" [x] Received");
   console.log(JSON.parse(msg.content));
}, {noAck: true});
+10
var obj=JSON.parse( msg.content.toString())
console.log(obj.name);

var details={'name':'Stack','Age':18}
+2

Source: https://habr.com/ru/post/1532207/


All Articles