我有一些麻烦缠绕着解决这个问题的方法,我已经使用了一些基本的代码。
这只是为一个更大的项目测试一些功能,我试图找到一种方法来拥有一个接受填充了Canvas Objects的数组的函数。然后我需要它循环遍历这些画布对象,并创建一个缓冲区来写入文件。
由于某种原因,当我运行这个我认为我应该异步时,它最终只会多次保存最后一个条形码。
对我而言,我的saveBarcode()函数似乎是一个错误,其中toBuffer和writeFile函数运行异步,但是然后它们在toBuffer和writeFile函数中丢失了循环的迭代值。
我似乎无法找到一种更好的方法来保存所有这些条形码画布'到文件。
任何输入都将非常感谢!如果您需要更多细节,我会尽我所能回答所有问题。
以下是整个代码:
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);
&#13;