Converting byte array to string

9.7k Views Asked by At

I am using ssh2 to execute ls -1 command on remote computer and get response like byte array. I convert to string with function

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

but when I try to split resulted/converted string by newline it doesn't work. (I have tried and asked on stackoverflow how to split and tried all solutions but it doesn't work, different results like add \ at the beginning and similar but doesn't split). I think maybe I convert on wrong way. Did anyone use ssh2 for return and how to convert that array to string.

2

There are 2 best solutions below

0
Andrey Sidorov On

Use Buffer.toString() method on your buf

0
Ronnie Royston On

You might try Node's implementation of the standard Web Crypto API which includes the TextDecoder() method for converting byte arrays into strings.

In terms of splitting strings on newline characters, there are several good examples of this on StackOverflow, e.g. here.

The TextDecorder method is illustrated pretty well on MDN.

let utf8decoder = new TextDecoder(); // default 'utf-8' or 'utf8'

let u8arr = new Uint8Array([240, 160, 174, 183]);
let i8arr = new Int8Array([-16, -96, -82, -73]);
let u16arr = new Uint16Array([41200, 47022]);
let i16arr = new Int16Array([-24336, -18514]);
let i32arr = new Int32Array([-1213292304]);

console.log(utf8decoder.decode(u8arr));
console.log(utf8decoder.decode(i8arr));
console.log(utf8decoder.decode(u16arr));
console.log(utf8decoder.decode(i16arr));
console.log(utf8decoder.decode(i32arr));