0

In order to tell NetworkManager to create a Wi-Fi access point over D-Bus using Node.js with the node-dbus library I need to provide an SSID as a byte array. As Node.js doesn't have the Blob class from client-side JavaScript my understanding is that I need to use a Buffer for this, but it's not working.

I can successfully turn a byte array into a string with the following code:

  let bytes = new Uint8Array(ssidBytes);
  let string = new TextDecoder().decode(bytes);

How do I reverse this to get a byte array from a string?

I've tried:

  let ssidBytes = Buffer.from(ssid);

And I've tried:

  let ssidBytes = [];
  for (let i = 0; i < ssid.length; ++i) {
    ssidBytes.push(ssid.charCodeAt(i));
  }

Assuming there isn't another error in my code (or the library I'm using), neither of these seem to have the desired effect.

For more background information see https://github.com/Shouqun/node-dbus/issues/228 and https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/issues/663

Thanks

benfrancis
  • 391
  • 2
  • 4
  • "neither of these seem to have the desired effect." -- this is too vague to help. `Buffer.from(ssid);` is correct. So what is wrong with the result? – Christian Fritz Oct 26 '21 at 20:26
  • Actually yes, I can confirm that by feeding the output of that function back into the first code snippet which converts it back into a string. So Buffer.from(ssid) does create a byte array, which must mean there's a problem somewhere else in my code. Thanks. – benfrancis Oct 27 '21 at 13:18
  • 1
    I discovered that Buffer.from(ssid) doesn't actually result in the byte array format expected by NetworkManager. However, I discovered a solution here: https://stackoverflow.com/a/36389863/1782967 – benfrancis Oct 29 '21 at 13:02

2 Answers2

0

I found the solution in another post, here https://stackoverflow.com/a/36389863/1782967

let ssid = 'my-ap';
let ssidByteArray = [];
let buffer = Buffer.from(ssid);
for (var i = 0; i < buffer.length; i++) {
  ssidByteArray.push(buffer[i]);
}
benfrancis
  • 391
  • 2
  • 4
0

A more compact solution that does the same:

const ssid = 'my-ap';
const ssidByteArray = Array.from(Buffer.from(ssid));
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71