11

I am using node.js amqp module for reading messages from a queue. The following is the callback that is invoked when there is a message available on the queue:

function onMessage(message, headers, deliveryInfo)
{
    console.log(message); //This prints buffer
    //how to convert message (which I expect to be JSON) into a JSON object.
    //Also how to get the JSON string from the 'message' which seems to be a buffer
}

Thanks.

Anand Patel
  • 6,031
  • 11
  • 48
  • 67

2 Answers2

13

If you receive a Buffer that contains JSON, then you'll need to convert it to a string to output something meaningful to the console:

console.log(message.toString())

If you want to convert that string to a full JavaScript object, then just parse the JSON:

var res = JSON.parse(message.toString())

Edit: node-amqp seems to be able to send directly JavaScript objects (see here), you shouldn't be receiving buffers but instead JavaScript objects... Check how you send your messages.

Paul Mougel
  • 16,728
  • 6
  • 57
  • 64
  • When I set message to {"name":"anand"} from rabbitmq console, console.log(message.toString()) is printing [object Object]. – Anand Patel Dec 17 '13 at 09:02
  • 1
    That's normal, see [`Object.toString()`'s documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString). If you see that, then you received a standard javascript object (most likely `{name: "anand"}`) and not a Buffer. What does `console.log(message)` outputs then? – Paul Mougel Dec 17 '13 at 09:07
  • Well, the messages aren't necessarily *sent* from node-amqp :) – Valentin Waeselynck Apr 07 '15 at 09:27
  • 1
    in server side: ch.sendToQueue(req.properties.replyTo, new Buffer( JSON.stringify( fResult) ), {correlationId: req.properties.correlationId}); so ,client side :const jsonResult = JSON.parse(result.content) ; //https://github.com/no7dw/rabbitmq-demo/blob/master/client_example.js – no7dw Aug 01 '16 at 14:00
12

message.data.toString() returned the appropriate JSON string.

Anand Patel
  • 6,031
  • 11
  • 48
  • 67