如何访问JavaScript中没有键的对象的值

问题描述

我正在尝试加载本地图像并将其转换为JavaScript中的Base64(不加载至浏览器)。当我运行以下代码时:

// 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

Base64字符串保存在“ image_base64”变量中。 “ image_base64”的数据类型是Object,但是没有任何Key。当我在控制台中打印“ image_base64”时:

{'/9j/4AAQSkZJRgABAQAAAQABAAD/4RDcRXhpZgA'}

(比上面更长。)

我想访问对象“ image_base64”内的Base64字符串。我尝试了以下命令:

console.log(Object.values(image_base64))   
console.log(image_base64[0])   

但是,他们返回:

[]
undefined

如果您知道如何访问对象内部的字符串,请告诉我。

解决方法

您得到的输出不是有效的vase64编码。您可以通过将数据输入到online base64 decoder中来进行检查。

imageToBase64()方法是异步的,并返回您未等待的承诺。

看看这样做会得到什么样的输出:

imageToBase64(image_path)
    .then(function(image_base64) {
        console.log(image_base64);
    })
    .catch(function(error) {
        console.error(error);
    });

如果您在ES6环境中,则可以await做出承诺:

// 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);
    }
}
,

我已经检查了这个库,您从 imageToBase64 函数收到的值是可以保证的。要从promise中获取价值,您可以执行以下操作-

let img64 = img64Lib(imgPath);
img64.then(result => {
    console.log(result);
}).catch(err => console.log(err));