Search code examples
javascriptnode.jstypescriptbuffer

Access Buffer - Javascript


I have this very simple code written in javascript.

 let str = "Hello World";
console.log(Buffer.from(str,"utf-8"));

result: <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>

How can i get the bytes from the Buffer? So result will look like this

expected result 48656c6c6f20576f726c64


Solution

  • Node's Buffer includes a toString method for this purpose. You can supply the desired encoding format as the first argument. In your case, you can use "hex" meaning hexadecimal:

    const str = 'Hello World';
    const buf = Buffer.from(str, 'utf-8');
    const hex = buf.toString('hex');
    console.log(hex === '48656c6c6f20576f726c64'); // true