'Koa / Strapi not returning pdfs from the local drive

This is driving me nuts....

I have a strapi instance, one endpoint of which is being used to return a pdf file. pull the file from S3 and then pass it directly to the ctx.request.body, then it returns correctly without issue. If however I save the file to the local hard drive for encrypting then neither the original or processed file being passed to the body results in anything other than a 404 error....

This works...

          ctx.set("Content-Type", "application/pdf");
          ctx.type = "pdf";
          const pdf = s3.getObject(params).createReadStream();
          console.log({pdf})
          ctx.response.body = pdf;

This doesn't...


            fs.writeFile(inputFilePath, pdf,'binary', (err) => {
            if (err) {
                console.log(err)
            } else {
                console.log("File written successfully")

                const encrypt = async () => {
                    const options = {
                        input: inputFilePath,
                        keyLength: 256,
                        output: outputFilePath,
                        password: {user: process.env.LOCKED_PASSWORD, owner: process.env.LOCKED_PASSWORD},

                    }
                    await qpdf2.default.encrypt(options)
                }
                try {
                    encrypt().then(()=>{
                        console.log("encrypted file exists", {outputFilePath})
                        const stat = fs.statSync(outputFilePath);
                        console.log({stat},{ctx})
                        ctx.set("Content-Type", "application/pdf");
                        ctx.set('Content-Length', stat.size)
                        ctx.type = "pdf";
                        ctx.response.body = fs.createReadStream(outputFilePath);               
                        
                    }).then(()=>{
                        setTimeout(() => {
                            console.log("Deleteing");
                            fs.unlinkSync(inputFilePath);
                            fs.unlinkSync(outputFilePath);
                          }, 3000);
                        
                    })
                } catch (err) {console.log(err)}
            }
            });

Anybody got any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source