Currently, I need to save a PDF hosted on S3 locally in NodeJS. I’m able to get the base64 fine from AWS, but the issue is when I convert the base64 to binary and write to file stream, the resulting PDF file is broken. Looking at the file in VS Code, I see the base64 string instead of binary data. I confirmed that before I wrote to the file stream that the base64 was in binary before being passed, but still no luck.
This is the current set up I have. I’ve checked a few other Stack Overflow posts like
How to save pdf in proper encoding via nodejs
How to save file from S3 using aws-sdk v3
However, those solutions still resulted in a broken PDF file. I’ve confirmed that the file exists in S3 and do receive the base64 string properly. The issue seems to be with writing the file locally on server side. I’m able to preview the file client side on Angular fine.
s3.getObject(params, (err, data) => {
if(err) {
res.status(400).send(err);
return;
}
const downloadPath = path.join(__dirname, "output.pdf");
downloadPDF(buffer, downloadPath)
...
})
const downloadPDF = async (data, downloadPath) => {
try {
let bufferDecoded = await Buffer.from(data.buffer, 'base64');
console.log("Data: ", bufferDecoded);
await fs.writeFileSync(downloadPath, bufferDecoded);
} catch (err) {
console.error("Error downloading file:", err);
}
};
0