Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert AQMP message buffer into JSON object when using node.js amqp module?

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.

like image 675
Anand Patel Avatar asked Dec 17 '13 06:12

Anand Patel


People also ask

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

The Buffer. toJSON() method returns the buffer in JSON format. Note: The JSON. Stringify() is the method which can also be used to return the data in JSON format.

How to convert Buffer data into string in Nodejs?

In a nutshell, it's easy to convert a Buffer object to a string using the toString() method. You'll usually want the default UTF-8 encoding, but it's possible to indicate a different encoding if needed. To convert from a string to a Buffer object, use the static Buffer.

What does the BUF toJSON () method return in node JS?

The Buffer. toJSON() method returns the buffer object as JSON object.

How convert Buffer to string in react native?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.


2 Answers

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.

like image 55
Paul Mougel Avatar answered Sep 27 '22 20:09

Paul Mougel


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

like image 40
Anand Patel Avatar answered Sep 27 '22 19:09

Anand Patel