简体   繁体   中英

Convert array of nested objects to Buffer Nodejs

1) Why ? i need pass buffer to rabbitMQ, publish method http://www.squaremobius.net/amqp.node/channel_api.html#channel_publish
2) my data look like this below

[ // array of objects
  {
    id: 1,
    name: 'John Doe',
    prop: {
      a: [....], // nested
      b: [....],
      c: {...}
    }
  },
  ...
]

How properly convert array of objects like this to buffer, so from the other side could parse back.

1) Why ?

From https://www.rabbitmq.com/tutorials/amqp-concepts.html#messages

AMQP messages also have a payload (the data that they carry), which AMQP brokers treat as an opaque byte array. The broker will not inspect or modify the payload. It is possible for messages to contain only attributes and no payload. It is common to use serialisation formats like JSON, Thrift, Protocol Buffers and MessagePack to serialize structured data in order to publish it as the message payload. AMQP peers typically use the "content-type" and "content-encoding" fields to communicate this information, but this is by convention only.

the TL;DR version of this is that RabbitMQ doesn't know anything about your data or how it's formatted / encoded. It treats your message as an array of bytes, requiring you to handle the encoding.

The amqp.node library wants you to pass a buffer around, because that's the easiest way for Node.js to handle the translation to and from a byte array, like RabbitMQ expects.

How properly convert array of objects like this to buffer, so from the other side could parse back.

In your message producer, you need to convert the message data into a JSON string (document) and then create a buffer from that.

var data = [ ... ];
var json = JSON.stringify(data);
var buffer = Buffer.from(json);

On the message consumer side, you would do the opposite, using the message body , and turn the buffer into a string , first.

var json = message.body.toString();
var data = JSON.parse(json);

At this point, your data object should be the array of data you want, for your Node.js code to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM