Based on how memory allocation works, you need to add the index into an complex type. So you need a findex object:
findex = { value: 0 }
When you modify the value, it saves it on the object findex which remains at the same adress space
function Base64toPDFandSave (base64String, filename) {
const fs = require('fs');
const path = require('path');
// Remove the prefix if it exists
const base64Data = base64String.replace(/^data:application\/pdf;base64,/, "");
// Define the path to save the PDF file on the user's desktop
const desktopPath = path.join(require('os').homedir(), 'Desktop');
const filePath = path.join(desktopPath, filename);
// Write the PDF file
fs.writeFile(filePath, base64Data, 'base64', (err) => {
if (err) {
console.error('Error saving the file:', err);
} else {
console.log('PDF file saved successfully at:', filePath);
}
});
}
function JsontoBase64 (jsonData, filename) {
// Verifica se jsonData é um objeto
if (typeof jsonData !== 'object' || jsonData === null) {
throw new Error("Entrada inválida: deve ser um objeto JSON.");
}
// Função recursiva para percorrer o JSON e encontrar os campos "BytesBoleto"
function procurarBytesBoleto(obj, fname, findex) {
for (const key in obj) {
console.log("......")
console.log(key + "::" + findex.value);
if (obj.hasOwnProperty(key)) {
if (key === 'BytesBoleto' && typeof obj[key] === 'string') {
findex.value= findex.value+1;
console.log("BytesBoleto:"+findex.value);
Base64toPDFandSave(obj[key], fname+findex.value.toString()+'.pdf');
} else if (typeof obj[key] === 'object') {
console.log("Recursiva:"+findex.value);
procurarBytesBoleto(obj[key], fname, findex); // Chama a função recursivamente
}
}
}
}
const findex = { value: 0}
procurarBytesBoleto(jsonData, filename, findex);
}
JsontoBase64 (jsonobj, 'boleto');