b64-to-blob icon indicating copy to clipboard operation
b64-to-blob copied to clipboard

atob is not defined, When using with nodeJS backend

Open prionkor opened this issue 6 years ago • 9 comments

As the title says..

prionkor avatar Oct 31 '18 08:10 prionkor

yes! I have the same problem as well.

samad324 avatar Dec 03 '18 16:12 samad324

ReferenceError: atob is not defined

TonyRenHK avatar Dec 08 '18 16:12 TonyRenHK

Hello, I have the same issue. Could you please tell if the issue has been solved? I thank you

praVishal2910 avatar Mar 25 '19 10:03 praVishal2910

no! but I found another way to do it!

samad324 avatar Mar 25 '19 10:03 samad324

Can you please share your solution?

hoh-yue avatar Jul 11 '19 16:07 hoh-yue

fix :

npm install atob --save global.atob = require("atob"); and npm i node-blob --save global.Blob = require('node-blob');

leb90 avatar Oct 02 '19 18:10 leb90

Hi you can use Buffer function on nodejs like this:

  const buf = Buffer.from("hello world", "utf8");
  const base64Encode = buf.toString("base64");
  console.log(base64Encode);
  // Prints: aGVsbG8gd29ybGQ=

  const base64Decode = Buffer.from(base64Encode, "base64");
  console.log(base64Decode);
  // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
  //                 h  e  l  l  o     w  o  r  l  d

note: this example is for nodejs new version. Buffer.from > V6.0.0 new Buffer < V6.0.0

doc link : https://nodejs.org/dist/latest-v12.x/docs/api/buffer.html

MahdadGhasemian avatar Sep 05 '20 06:09 MahdadGhasemian

Just for completenes, use toString() on your base64 to obtain the string :)

        console.log(base64Decode.toString());

MaxHammermann avatar Nov 07 '21 11:11 MaxHammermann

Hi, I have rewrite the function using Buffer like @MahdadGhasemian In Windows it fail here slice.charCodeAt(i); with error: Uncaught TypeError: slice.charCodeAt is not a function at b64toBlob (misc.js:210:1)

This error not exist with atob version

/**
 * Convert 64bit url string to Blob
 * @name b64toBlob
 * @method
 * @param {string} b64Data - the 64bit url string which should be converted to Blob
 * @param {string} contentType - content type of blob
 * @param {int} sliceSize - optional size of slices if omited 512 is used as default
 * @returns {Blob}
 * TODO charCodeAt is not a function at Windows
 */
function b64toBlob(b64Data, contentType = "", sliceSize = 512) {
  const byteCharacters = Buffer.from(b64Data, "base64"); // atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.subarray(offset, offset + sliceSize);
    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i += 1) {
      byteNumbers[i] = slice.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  return new Blob(byteArrays, { type: contentType });
}

sytolk avatar Aug 12 '22 09:08 sytolk