<!--This code is used to generate a bar code, create an image file and then make the file available for download in the browser-->
bwipjs.loadFont('Inconsolata', 108, require('fs').readFileSync('node_modules/bwip-js/fonts/Inconsolata.otf', 'binary'));
bwipjs.toBuffer({
bcid: 'code128',
text: 'ID:' + result[0]._id + '\nDevice Name:' + result[0].device_name + '\nDevice Model' + result[0].device_model,
scaleX: 0.5,
scaleY: 0.5
}, function(err, png) {
if (err) {
console.log("Error in generating barcode");
console.log(err.stack);
}
fs.writeFile('images/' + device + '.png', png, function(err) {
if (err) {
return console.error(err);
}
});
res.download('images/' + device + '.png', device + 'png', function(err) {
if (err) {
console.log("Error:");
return console.error(err);
}
});
});
Asked
Active
Viewed 332 times
-1

Terry Burton
- 2,801
- 1
- 29
- 41

Samin Batra
- 1
- 1
1 Answers
0
writeFile
is async. You need to move download part into callback
bwipjs.loadFont('Inconsolata', 108, require('fs').readFileSync('node_modules/bwip-js/fonts/Inconsolata.otf', 'binary'));
bwipjs.toBuffer({
...
function(err, png) {
if (err) {
console.log("Error in generating barcode");
console.log(err.stack);
}
fs.writeFile('images/' + device + '.png', png, function(err) {
if (err) {
return console.error(err);
}
else { // run when file was written to disk
res.download('images/' + device + '.png', device + 'png', function(err) {
if (err) {
console.log("Error:");
return console.error(err);
}
});
}
});
});

Yury Tarabanko
- 44,270
- 9
- 84
- 98