loop through barcodes canvas to create buffer and write to file

442 Views Asked by At

I'm having some troubles wrapping my head around a way to solve this problem ive been having with some basic code.

This is just testing some functionality for a bigger project, and i am trying to find a way to have a function that accepts an array filled with Canvas Objects. and then i need it too loop through those canvas objects, and create a buffer to write to a file.

For some reason when i run this how i think i should asynchronously, it only ends up saving the very last barcode multiple times.

To me it appears to be an error with my saveBarcode() function, in which the toBuffer and writeFile functions run async, but then they lose the iteration value of the loop im using within the toBuffer and writeFile functions.

I cant seem to figure out a better way to save all these barcode canvas' to files.

Any input would be much appreciated! If you need any more details i will answer everything to the best of my ability.

Here is the entire code:

const JsBarcode = require("jsbarcode");
const Canvas = require("canvas");
const fs = require("fs");

//makeid creates a Random 12 Digit # to represent the barcode number, It returns an Array of barcodes based on the amount inputted
let makeid = (amount) => {
  let barcodeArray = [];
  let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  for (ii = 0; ii < amount; ii++) {
    let text = "";
    for (var i = 0; i < 12; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    barcodeArray.push(text);
  }

  return barcodeArray;
}

//createCanvas will take the random barcode array, and will create multiple barcode canvas' and will return an array of the amount of canvas' specified
let createCanvas = (barcodes, amount) => {
  let canvas = new Canvas();
  let canvasArray = [];

  for (iii = 0; iii < amount; iii++) {
    let canvas2 = JsBarcode(canvas, barcodes[iii], {
      width: 2,
      height: 100,
      displayValue: true,
      text: barcodes[iii],
      textAlign: "center"
    });
    canvasArray.push(canvas2._renderProperties.element);
  }
  console.log(barcodes);
  return canvasArray;
}

//saveBarcodes will take the canvas Array returned from createCanvas Function and will create a buffer for each, then write that buffer to an image file.
let saveBarcodes = (canvasBarcodes, amount) => {
  for (iiii = 0; iiii < amount; iiii++) {
    canvasBarcodes[iiii].toBuffer((err, buf) => {
      console.log(buf);
      fs.writeFile("image" + iiii.toString() + ".png", buf, err => {
        if (err == null) {
          console.log("Successfully wrote: image" + iiii + ".png");
        } else {
          console.log(err);
        }
      });
    });
  }
}

let renderedBarcodes = createCanvas(makeid(12), 12);
saveBarcodes(renderedBarcodes, 12);

0

There are 0 best solutions below