Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs zmq - received buffer data than actual message

Tags:

node.js

zeromq

I am doing the example of pubsub from this link and managed to get it work.

server.js:

const zmq = require("zeromq")

async function run() {
  const sock = new zmq.Publisher

  await sock.bind("tcp://127.0.0.1:3000")
  console.log("Publisher bound to port 3000")

  while (true) {
    console.log("sending a multipart message envelope")
    await sock.send(["kitty cats", "meow!"])
    await new Promise(resolve => setTimeout(resolve, 500))
  }
}

run()

client.js:

const zmq = require("zeromq")

async function run() {
  const sock = new zmq.Subscriber

  sock.connect("tcp://127.0.0.1:3000")
  sock.subscribe("kitty cats")
  console.log("Subscriber connected to port 3000")

  for await (const [topic, msg] of sock) {
    console.log("received a message related to:", topic, "containing message:", msg)
  }
}

run()

so I expect the log from client.js to be:

received a message related to: kitty cats containing message: meow!

but get this instead:

received a message related to: <Buffer 6b 69 74 74 79 20 63 61 74 73> containing message: <Buffer 6d 65 6f 77 21>

Is this normal? or is there a way to get back my message in string form?

like image 399
sooon Avatar asked Oct 14 '25 07:10

sooon


1 Answers

You will want to convert a Buffer to string with toString() (defaults to utf-8 encoding)

or you can use string-decoder from nodejs

with stringDecoder.write(buffer)

i.e. stringDecoder.write(topic)

const zmq = require("zeromq")

async function run() {
  const sock = new zmq.Subscriber

  sock.connect("tcp://127.0.0.1:3000")
  sock.subscribe("kitty cats")
  console.log("Subscriber connected to port 3000")

  for await (const [topic, msg] of sock) {
    console.log("received a message related to:", topic.toString("utf=8"), "containing message:", msg.toString("utf-8")
  }
}

run()
like image 151
Denis Tsoi Avatar answered Oct 18 '25 05:10

Denis Tsoi