0

Per https://www.jsonrpc.org/specification I need a JSON object returned as a byte array, contatenated with <0x00>.

Consider this object:

{"jsonrpc":"2.0","method":"StatusGet","id":"1","params":0}

Returned as <0x00>-terminated byte array:

[123,34,106,115,111,110,114,112,99,34,58,34,50,46,48,34,44,34,109,101,116,104,111,100,34,58,34,83,116,97,116,117,115,71,101,116,34,44,34,105,100,34,58,34,49,34,44,34,112,97,114,97,109,115,34,58,48,125,0]

From examples found elsewhere, here's what I currently have that works (in a Nodered function node, which is fed into a TCP request node):

function fnStringMessage(str){
    
    let bytes = Buffer.from(str)
    bytes = []
    for (let i=0; i<str.length; i++){
        bytes.push(str.charCodeAt(i))
    }
    bytes.push(0)

    return (bytes)
}

let ss = JSON.stringify(msg.payload)

msg.payload = Buffer.from(fnStringMessage(ss))

return msg;

However I'm a noob and using a for loop looks a bit turtle to me. Looking for the hare, and any other suggestions to simplify this further. Thanks

  • 1
    Do you have any specific problem with this code? How do you know it's slow? What is it that you compare this code with? – Parzh from Ukraine Mar 22 '22 at 20:42
  • The "turtle" in term of performances here is probably the JSON.stringify call. Anyway, if you want code "elegance", you can probably use `.map`, but it would probably be slower in execution time than building your array. Also, it is useless in your case to initialise with `Buffer.from(str)`, since you just overwrite it with an empty array right after. Of course, all debate or arguments on actual performance should be actually benchmarked properly. – Pac0 Mar 22 '22 at 20:43
  • DId you check https://stackoverflow.com/questions/6226189/how-to-convert-a-string-to-bytearray ? – James Mar 22 '22 at 20:48
  • No problem with it working, I just can't help thinking that the data is already there in memory and I should just be able to at best get a pointer to it, or at worst at least skip a couple of 'loop conversion' steps. – Duckminster Mar 29 '22 at 15:23

1 Answers1

0

You can append a zero byte to the string, then convert that into a Buffer.

function fnStringMessage(str){
  return Buffer.from(str + "\0");
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Tested and works, and also helps me better understand how BLOBS can be easily manipulated at the byte level without loopy type conversions chained together. Thank you! It also appears to run faster in my tests than the push/loop method shown in many other examples. – Duckminster Mar 29 '22 at 14:51