使用node.js amqp模块时如何将AQMP消息缓冲区转换为JSON对象?

时间:2013-12-17 06:39:06

标签: node.js type-conversion node-amqp

我使用node.js amqp模块从队列中读取消息。以下是队列中有可用消息时调用的回调:

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
}

感谢。

2 个答案:

答案 0 :(得分:12)

如果您收到包含JSON的Buffer,那么您需要将其转换为字符串以输出对控制台有意义的内容:

console.log(message.toString())

如果要将该字符串转换为完整的JavaScript对象,则只需解析JSON:

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

编辑: node-amqp似乎能够直接发送JavaScript对象(参见here),你不应该接收缓冲区而是JavaScript对象...检查你是怎么做的发送你的消息。

答案 1 :(得分:11)

message.data.toString()返回了相应的JSON字符串。