Rachid Oussanaa Rachid Oussanaa - 1 year ago 125
Node.js Question

Spread operator on a Buffer object

Can someone please explain how does this code work:


the result is:

[ 97, 98, 99 ]

Answer Source

First of all, consider this piece of shit:

console.log([...[1, 2, 3]]); //[1, 2, 3]

The Spread operator will try to take an array and transform it to a list of arguments.

Node.js's buffer object are actually arrays of bytes, a way to represent character and deal with binary data simultaneously. you can read more about it at https://nodejs.org/api/buffer.html.

Now, since 'abc' is actually three ascii characters, each one will only take up one byte, and that byte will correspond to its ascii code. You can get this by doing: myString.charCodeAt(pos), in your case 'abc'.charCodeAt(0) will return 97.



will actually return an array containing the ascii codes of each character of 'abc'. that is [97, 98, 99]

Since buffers' encoding is by default UTF-8, things will get more exciting when you are dealing with unicode.

console.log([...Buffer('漢字')]); //[230 188 162 229 173 151]

Sorry for potential typos and hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download