How to convert ref-struct of nodejs to Buffer?

in nodejs, you need to send structural data to the C process through socket, using
https://www.npmjs.com/package.

.

but when sending an error, only Buffer: is recognized

.
var net = require("net");
var ref = require("ref")
var StructType = require("ref-struct")

var MyDataHead = StructType({
  type: ref.types.uint,
  len: ref.types.uint,
  state: ref.types.int
})

var head = new MyDataHead
head.type = 1
head.len = 0
head.state = 0

var sockfile = "/var/run/xxx.sock"
var client = net.connect({path: sockfile}, function() {
  //"connect" listener
  console.log("connected to server!");
  client.write(head);
});

client.on("data", function(data) {
  console.log(data.toString());
  client.end();
});

client.on("end", function() {
  console.log("disconnected from server");
});

TypeError: Invalid data, chunk must be a string or buffer, not object

Mar.17,2021
Change

to var head = ref.alloc (MyDataHead)


1. Use ref () to get buffer
const struct = new myStruct ({id:2})
const buffer = struct.ref ()

2.PS: the buffer
const buffer = struct ['ref.buffer']

3 of the current structure can also be obtained from the ref.buffer property of struct. Read the structure from buffer
const newStruct = new myStruct (buffer)

Menu