Monday 22 July 2019

Help, please. Values are not reassigned during loop iteration. This is my first node project and I think I may be stuck on asynchronous js concepts.

I have variables assigned in the first loop within the get request (like requestNo). The variables are not reassigned after each iteration. I am tracking the promised status of each pdf process and after the loop waiting for the promises to be settled before archiving all the PDFs.const express = require('express'); const pdftk = require('node-pdftk'); const archiver = require('archiver'); const Q = require('q'); const fs = require('fs'), path = require('path'), pdfFilePath = path.join(__dirname, 'VisaApplication.pdf'); const app = module.exports = express(); const code128 = [' ','!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó']; app.get('/VisaApplications.zip/:amount*?', function(req, res) { debugger; let amount = req.params.amount; let archive = archiver('zip'); let promises = []; archive.pipe(res); archive.on('error', function(err) { throw err; }); if (!amount) { amount = 1; } for ( let i = 0; i < amount; i++ ) { let date = new Date(); let datetime = date.getTime(); let seconds = datetime / 1000; let timestamp = Math.floor(seconds); let checksum = 103; let sNumber = timestamp.toString(); let randInt = Math.floor(Math.random() * 9999) + 1; let requestNo = randInt + sNumber for (let j = 0, len = requestNo.length; j < len; j += 1) { checksum += code128.indexOf(requestNo.charAt(j)) * j + 1; } checksum %= 103; let barcode1 = code128[103] + requestNo + code128[checksum] + code128[106]; let barcode2 = '* ' + requestNo + ' *'; promises.push( pdftk .input(pdfFilePath) .fillForm({ request_no: requestNo, Barcode1: barcode1, Barcode2: barcode2, }) .output() .then(buffer => { filename = 'VisaApplication' + (i + 1) + '.pdf'; archive.append(buffer, { name: filename }); }) .catch(err => { throw err; }) ); } res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'attachment; filename=VisaApplications.zip' }); Q.allSettled(promises).done(function() { archive.finalize(); }); }); if (require.main === module) { app.listen(process.env.PORT || 5000, () => { console.log('Visa Application Zip Export App running on ' + process.env.PORT || 5000); }); }

Submitted July 22, 2019 at 11:38PM by updateSeason

No comments:

Post a Comment