buffer icon indicating copy to clipboard operation
buffer copied to clipboard

NodeJS Buffer returns different result for same operation

Open NunoSav opened this issue 3 years ago • 1 comments

I've recently switched to this library on a @ionic/vue app and since then some of my unit tests fail since they run under node environment. The following is an example that returns a different value depending on where it runs on.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Buffer</title>
  </head>
  <body>
    <script src="https://bundle.run/[email protected]"></script>
    <script defer>
      const { Buffer } = window.buffer;
      const intInBase64 = "/w==";

      function decodeBase64ToInt(value) {
        const buf = Buffer.from(value, 'base64');
        const bytes = new Int8Array(buf.buffer);

        return bytes[0];
      }

      console.log(decodeBase64ToInt(intInBase64))
    </script>
  </body>
</html>
const intInBase64 = "/w==";

function decodeBase64ToInt(value) {
  const buf = Buffer.from(value, 'base64');
  const bytes = new Int8Array(buf.buffer);

  return bytes[0];
}

console.log(decodeBase64ToInt(intInBase64))

Running the HTML snippet on the browser will return -1 and running the second snippet with node will return 47. How come?

NunoSav avatar Jan 07 '22 10:01 NunoSav

Anybody has any idea why since I'm having the same issue. I'm having the same issue with browerify version, Buffer.from value is different between NodeJS and browserify version that is plugged into browser.

0x520x650x78 avatar May 04 '22 19:05 0x520x650x78