I'm struggling with a Node.js script that's supposed to save PDF files from Base64 encoded data. The code aims to extract 'BytesBoleto' fields from a JSON object, decode them, and save the resulting PDFs to the user's desktop. However, I'm getting an error:
"The 'data' argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of File"
Here's a simplified version of what I'm trying to do:
```javascript
function processPDFs(jsonData) {
const pdfData = [];
function findPDFs(obj) {
for (let key in obj) {
if (key === 'PDFContent' && typeof obj[key] === 'string') {
const decoded = Buffer.from(obj[key], 'base64');
pdfData.push({ name: `${key}.pdf`, content: decoded });
} else if (typeof obj[key] === 'object') {
findPDFs(obj[key]);
}
}
}
findPDFs(jsonData);
return pdfData;
}
// Usage example
const sampleData = {
docs: [
{ PDFContent: 'base64encodeddata1' },
{ PDFContent: 'base64encodeddata2' }
]
};
const pdfs = processPDFs(sampleData);
// Now I want to save these PDFs, but it's not working
Can someone point out what I’m doing wrong or suggest a better approach?
I’ve dealt with a similar issue before, and I think I see where the problem might be. Your code for processing the PDFs looks fine, but the error suggests you’re trying to write a File object instead of the Buffer you’ve created.
Here’s what worked for me:
After you get your pdfs array, you need to use the fs module to write each PDF to disk. Something like this:
const fs = require('fs');
const path = require('path');
pdfs.forEach(pdf => {
const desktopPath = path.join(require('os').homedir(), 'Desktop');
const filePath = path.join(desktopPath, pdf.name);
fs.writeFile(filePath, pdf.content, (err) => {
if (err) throw err;
console.log(`${pdf.name} has been saved to the desktop`);
});
});
This should write your PDFs to the desktop without any type errors. Make sure you have the necessary permissions to write to the desktop folder. If you’re still having issues, double-check that your Base64 data is valid and complete. Hope this helps!
hey, looks like ur on the right track. one thing to watch out for - make sure ur not accidentally passing a File object instead of the Buffer. double-check where ur getting that base64 data from. also, try using fs.writeFileSync instead of writeFile for simplicity. good luck mate!
I’ve encountered similar issues when working with Base64-encoded PDFs. One thing that stands out is the error message mentioning a ‘File’ instance. This suggests there might be a mismatch between what you’re passing and what the function expects.
A potential solution is to ensure you’re consistently working with Buffer objects throughout your code. After decoding the Base64 string, you could try explicitly creating a new Buffer:
If issues persist, consider logging the type of ‘obj[key]’ before decoding to ensure it’s indeed a string. These adjustments should help resolve the type mismatch and allow for successful PDF saving.