节点中的临时目录不随机工作.有时有效,但有时无效



我在Firebase web应用程序中使用GCP函数。我在正确访问tmp目录时遇到问题。我做错了什么?(奇怪的是,代码似乎也是随机工作的。(

const tmp = os.tmpdir();
const PdfPrinter = require('pdfmake');
const fs = require('fs');
const tmp = os.tmpdir()
const dd = [] 
const pdfDoc = printer.createPdfKitDocument(dd);
pdfDoc.pipe(fs.createWriteStream(`${tmp}/relative.pdf`));
pdfDoc.end();
const attachment = fs.readFileSync(`${tmp}/relative.pdf`).toString("base64"); // error here

错误:

Error: ENOENT: no such file or directory, open '/tmp/relative.pdf'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at /workspace/index.js:494:27
at processTicksAndRejections (node:internal/process/task_queues:96:5) 

这是我最终得到的答案。我有两个附件,我需要等到它们完成。

我最终切换到使用Buffer,但我认为我本可以使用tmp目录,它会起作用。从本质上讲,该函数在运行完成之前刚刚关闭。所以,我安排了一些检查,以确保一切都完成了。

const docDefinition = {
// normal doc definition
}
const pdfDoc = printer.createPdfKitDocument(docDefinition);
const pdfTitle = workOrder.replace(/[^a-zA-Z0-9 ]/g, '')
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
let attachment
pdfDoc.on('end', () => {
const result = Buffer.concat(chunks);
attachment = {
content: result.toString('base64'),
filename: `Estimate-${pdfTitle}.pdf`,
type: "application/pdf",
disposition: "attachment"
}
});
pdfDoc.on('error', (err) => {
console.log(err);
});
pdfDoc.end();
const printer_2 = new Printer(fontDescriptors);
const chunks_2 = [];
const docDefinition_2 = {
// normal doc definition
}
const pdfDoc_2 = printer_2.createPdfKitDocument(docDefinition_2);
pdfDoc_2.on('data', (chunk) => {
chunks_2.push(chunk);
});
let attachment_2
pdfDoc_2.on('end', () => {
const result_2 = Buffer.concat(chunks_2)
attachment_2 = {
content: result_2.toString('base64'),
filename: `Lumber-order-${pdfTitle}.pdf`,
type: "application/pdf",
disposition: "attachment"
}
});
pdfDoc_2.on('error', (err) => {
console.log(err);
});
pdfDoc_2.end();
functions.logger.log('Log Before Interval Start')

这段代码确保函数不会在两个附件准备好之前终止。

async function waitUntil() {
return await new Promise(resolve => {
const interval = setInterval(() => {
if (attachment && attachment_2) {
clearInterval(interval)
functions.logger.log('Attachments Ready')
let attachments = []
attachments.push(attachment)
attachments.push(attachment_2)
const msg = {
// to, from, etc.. here
attachments: attachments
};
resolve(msg)
}
}, 1000)
})
}
const msg = await waitUntil()
const resp = await sgMail.send(msg)

我遇到了一个非常类似的问题。我用excel4node框架创建了一个xlsx文件,然后我想阅读它,并将其作为附件发送。我遇到了和你读文件时一样的错误。我的工作也是随机的。

我找不到一个合理的解决方案,但在阅读文件之前添加一个小延迟似乎可以解决它

// Function that creates the file and stores it in the /tmp-folder
await createExcelFile() 
// This solved it for me, add a small delay
await new Promise(f => setTimeout(f, 1000));
// Read the file again from tmp-folder
const pathToAttachment = "/tmp/" + reportFileName;
const attachment = fs.readFileSync(pathToAttachment).toString("base64"); 

相关内容

最新更新