I am trying to load a local image and convert it into Base64 in JavaScript (without loading into browser). When I run the following code:
// https://www.npmjs.com/package/image-to-base64 // installation: npm i -S image-to-base64 const image_path = "1.jpg" // Path to the image const imageToBase64 = require('image-to-base64'); const image_base64 = imageToBase64(image_path) console.log(typeof image_base64) // object
Th Base64 string is saved in “image_base64” variable. The data-type of “image_base64” is Object, but it doesn’t have any Key. When I print “image_base64” in console:
{'/9j/4AAQSkZJRgABAQAAAQABAAD/4RDcRXhpZgA'}
(It is much longer than above.)
I want to have access to the Base64 string inside the Object “image_base64”. I tried the following commands:
console.log(Object.values(image_base64)) console.log(image_base64[0])
But, they return:
[] undefined
If you have any idea how I can get access to the string inside the Object, please let me know.
Advertisement
Answer
The output you are getting is not valid vase64 encoding. You can check this by entering the data into an online base64 decoder.
The imageToBase64() method is asynchronous and returns a promise which you are not awaiting.
See what kind of output you get from doing this:
imageToBase64(image_path) .then(function(image_base64) { console.log(image_base64); }) .catch(function(error) { console.error(error); });
If you’re in an ES6 environment, you can await
the promise:
// async function required for Node < v14 async function convertImage(image_path) { try { const image_base64 = await imageToBase64(image_path); // Do something with image_base64 data console.log(image_base64); } catch (error) { console.error(error); } }