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

1

There are 1 answers

0
Yury Tarabanko On

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