I get an array of numbers as a response from remote command execution (using ssh2). How do I convert it to a string?
[97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]
I get an array of numbers as a response from remote command execution (using ssh2). How do I convert it to a string?
[97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]
var result = String.fromCharCode.apply(null, arrayOfValues);
Explanations:
String.fromCharCode can take a list of char codes as argument, each char code as a separate argument (for example: String.fromCharCode(97,98,99)
).
apply
allows to call a function with a custom this
, and arguments provided as an array (in contrary to call
which take arguments as is). So, as we don't care what this
is, we set it to null
(but anything could work).
In conclusion, String.fromCharCode.apply(null, [97,98,99])
is equivalent to String.fromCharCode(97,98,99)
and returns 'abc'
, which is what we expect.
It depends on what you want and what you mean.
Option One: If you want to convert the text to ASCII, do this:
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
theString = String.fromCharCode.apply(0, theArray);
(Edited based on helpful comments.)
Produces:
app.js
node.js
Option Two: If you just want a list separated by commas, you can do .join(',')
:
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var theString = theArray.join(',');
You can put whatever you want as a separator in .join()
, like a comma and a space, hyphens, or even words.
In node.js it's usually done with buffers:
> new Buffer([97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]).toString()
'app.js\nnode.js\n'
It'll be faster than fromCharCode, and what's most important, it'll preserve utf-8 sequences correctly.
just use the toString() function:
var yourArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var strng = yourArray.toString();
The ssh2 module passes a Buffer (not an actual javascript array) to 'data' event handlers for streams you get from exec() or shell(). Unless of course you called setEncoding() on the stream, in which case you'd get a string with the encoding you specified.
If you want the string representation instead of the raw binary data, then call chunk.toString()
for example.