Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在节点js中为kafka主题编写jsonArray_Node.js_Arrays_Json_Apache Kafka - Fatal编程技术网

Node.js 如何在节点js中为kafka主题编写jsonArray

Node.js 如何在节点js中为kafka主题编写jsonArray,node.js,arrays,json,apache-kafka,Node.js,Arrays,Json,Apache Kafka,如何将数组(包含json字符串)写入节点js中的Kakfa主题 server.on('package:publish', async event => { try { const responses = await producer.send({ topic: process.env.TOPIC, messages: [{ // Name of the published package as key, to make sure that

如何将数组(包含json字符串)写入节点js中的Kakfa主题

server.on('package:publish', async event => {
  try {
    const responses = await producer.send({
      topic: process.env.TOPIC,
      messages: [{
        // Name of the published package as key, to make sure that we process events in order
        key: event.name,

        // The message value is just bytes to Kafka, so we need to serialize our JavaScript
        // object to a JSON string. Other serialization methods like Avro are available.
        value: JSON.stringify(array)
      }]
    })

    console.log('Published message', { responses })
  } catch (error) {
    console.error('Error publishing message', error)
  }
})
消息值只是Kafka的字节数,因此我们需要序列化JavaScript 对象转换为JSON字符串。其他序列化方法(如Avro)也可用

只需将数组数据包装为JSON.stringify(array),并以值形式发送, 在消费端,您可以使用
JSON.parse(message.value)

这里有一些帮助链接