b64-to-blob
b64-to-blob copied to clipboard
atob is not defined, When using with nodeJS backend
As the title says..
yes! I have the same problem as well.
ReferenceError: atob is not defined
Hello, I have the same issue. Could you please tell if the issue has been solved? I thank you
no! but I found another way to do it!
Can you please share your solution?
fix :
npm install atob --save global.atob = require("atob"); and npm i node-blob --save global.Blob = require('node-blob');
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
Just for completenes, use toString()
on your base64 to obtain the string :)
console.log(base64Decode.toString());
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 });
}