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

Ana*_*tel 9 type-conversion node.js 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
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Pau*_*gel 12

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

console.log(message.toString())
Run Code Online (Sandbox Code Playgroud)

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

var res = JSON.parse(message.toString())
Run Code Online (Sandbox Code Playgroud)

编辑: node-amqp似乎能够直接发送JavaScript对象(见这里),你不应该接收缓冲区而是JavaScript对象...检查你如何发送你的消息.


Ana*_*tel 11

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