• in nodejs terminal:

    > var s = String.fromCharCode(0x00,0x2B,0x20,0xFC);
    > var t = new Buffer(s).toString('base64');
    > console.log(s);
    + ü
    > console.log(t);
    ACsgw7w=
    > 
    

    string is String.fromCharCode(0x00,0x2B,0x20,0xFC) , the base64 string is "ACsgw7w="

    and in Espruino Web IDE left-hand terminal:

    >var s = String.fromCharCode(0x00,0x2B,0x20,0xFC);
    ="\x00+ \xFC"
    >var t = btoa(s);
    ="ACsg/A=="
    

    string is String.fromCharCode(0x00,0x2B,0x20,0xFC) , the base64 string is "ACsg/A=="

    Why the same string gets different base64 encoded string in Espruino and nodejs?

  • The problem is actually with your node.js code :) If you look at what's in your buffer:

    > var s = String.fromCharCode(0x00,0x2B,0x20,0xFC);
    undefined
    > var b = new Buffer(s);
    undefined
    > b
    <Buffer 00 2b 20 c3 bc>
    > b.length
    5
    

    You'll see that it's magically turned the string into a 5 byte buffer. Most likely it's because it is interpreting your string as a UTF8 string, when I guess you intended to use it just as a string of bytes.

  • Yes.
    Just use 'ascii' to set the encoding format.

    Thanks a lot.

    > var s = String.fromCharCode(0x00,0x2B,0x20,0xFC);
    undefined
    > var b = new Buffer(s,'ascii');
    undefined
    > b
    <Buffer 00 2b 20 fc>
    > b.length
    4
    > b.toString('base64');
    'ACsg/A=='
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

base64 encode/decode: btoa() and nodejs Buffer work different way?

Posted by Avatar for Aifer @Aifer

Actions