循环通过条形码canvas创build缓冲区并写入文件

为了解决这个问题,我正在用一些基本的代码来解决这个问题。

这只是testing一个更大的项目的一些function,我试图find一种方法来接受一个数组填充canvas对象的函数。 然后我也需要循环这些canvas对象,并创build一个缓冲区来写入一个文件。

由于某种原因,当我运行这个如何,我认为我应该asynchronous,它只能保存最后的条码多次。

对我来说,我的saveBarcode()函数似乎是一个错误,其中toBuffer和writeFile函数运行asynchronous,但是它们在toBuffer和writeFile函数中失去了循环im的迭代值。

我似乎找不到一个更好的方式来保存所有这些条形码canvas'文件。

任何input将不胜感激! 如果你需要更多的细节,我会尽我所能回答一切。

这是整个代码:

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