简体   繁体   中英

How to create a barcode for each items in an array in Node.js?

I'm trying to create a barcode for each item in an array in Node.js but since bwip-js (which is the implementation I'm using as my function is hosted in AWS Lambda) only has an asynchronous method for toBuffer(), I don't know how I can accomplish my requirement.

Here's the code I have:

const bwipjs = require('bwip-js');
const test = () => {
    let items = [
        {
            name: "Item1",
            barcode: "8590345627"
        },
        {
            name: "Item2",
            barcode: "6812430976"
        },
        {
            name: "Item3",
            barcode: "5098453726"
        }
    ];
    for(let item of items){
        bwipjs.toBuffer({
            bcid: 'code128',
            text: item.barcode,
            scale: 3,
            height: 10,
            includetext: true,
            textxalign: 'center'
        }).then(buffer => {
            let barcodeBase64 = `data:image/gif;base64,${buffer.toString('base64')}`
            item.barcodeImage = barcodeBase64;
        }).catch(error=>{
            console.log("Error" + error);
        });
    }
    console.log(items);
};
test();

But I'm only getting this:

在此处输入图片说明

I would appreciate if someone can help me with the right approach for accomplishing my requirement.

Thank you in advance.

try await

const test = async ()=> {
    // .... blah blah
    for(let item of items){
       const buffer = await bwipjs.toBuffer(/* ... */)
       const barcodeBase64 = `data:image/gif;base64,${buffer.toString('base64')}`
       item.barcodeImage = barcodeBase64;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM