javascript - 将嵌套对象数组转换为 Nodejs Buffer

标签 javascript node.js object rabbitmq buffer

1) 为什么?我需要将缓冲区传递给rabbitMQ,发布方法http://www.squaremobius.net/amqp.node/channel_api.html#channel_publish
2)我的数据如下所示

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

如何正确地将这样的对象数组转换为缓冲区,以便从另一端可以解析回来。

最佳答案

1) Why ?

来自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.

这个版本的 TL;DR 版本是 RabbitMQ 不知道有关您的数据或其格式化/编码方式的任何信息。它将您的消息视为字节数组,要求您处理编码。

amqp.node 库希望您传递一个缓冲区,因为这是 Node.js 处理字节数组之间转换的最简单方法,就像 RabbitMQ 所期望的那样。

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

在消息生产者中,您需要将消息数据转换为 JSON 字符串(文档),然后 create a buffer由此而来。

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

在消息使用者方面,您可以执行相反的操作,使用消息bodyturn the buffer into a string ,首先。

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

此时,您的 data 对象应该是您想要的数据数组,供 Node.js 代码使用。

关于javascript - 将嵌套对象数组转换为 Nodejs Buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41187889/

相关文章:

javascript - 如何动态地将数组值作为对象属性传递?

c++ - 删除函数内的对象

javascript - Angular 2 : execute a function when the element appears on the screen

javascript - React - 在发布请求中发送存储的状态值 - 格式错误的数据

javascript - label元素的for属性的值必须是非隐藏表单控件的ID?

我自动将 Python 内容作为字段传递给类

javascript - Greasemonkey 脚本查找页面中某个域的所有 url 并进行更改

javascript - 如何在 webpack-dev-server 和express 服务器上重新加载模块?

c++ - 是否可以将 Thrift 代码转换为 Async

node.js - Sequelize 不加入关系