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

1k views Asked by At

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:

enter image description here

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

Thank you in advance.

1

There are 1 answers

1
lastr2d2 On

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;
    }
}