是否有必要在 Firebase Cloud Function 中释放内存

is it necessary to free memory in Firebase Cloud Function

我在 firebase 云函数上做了一些 POC,并用下面的代码片段制作了一个 CF(这是工作代码片段)。

app.post('/create-pdf', (req, res) => {
   pdfPromise.toFile( os.tmpdir() + '/template.pdf', (err, data) => {
       if(err) {
         console.log('Error Saving File', err);
         res.send(Promise.reject());
       }
       res.send(Promise.resolve());
    });
})

app.get('/get-pdf', (req, res) => {
    res.sendFile(`${os.tmpdir()}/template.pdf`);
})

上面api的调用会像这样。

axios.post(url+'/create-pdf', { data : poBody }).then((res) => {
}).then(() => {
    axios.get(url+'/get-pdf', { responseType: 'blob' }).then(res => {
        const pdfBlob = new Blob([res.data], { type: 'application/pdf' });
        saveAs(pdfBlob, 'payout.pdf')
    })
})

此代码运行良好.. 我只想知道服务器端代码是否在GCP上是运行作为CF,那么我们是否需要清除os.tmpdir()消耗的内存,还是会自动清除?

是的,您确实需要删除在临时目录(这是一个 in-memory 文件系统)中创建的临时文件,因为“您编写的文件会消耗函数可用的内存,有时会在调用之间持续存在".

有一个特定的文档部分和相关视频:https://firebase.google.com/docs/functions/tips#always_delete_temporary_files and https://www.youtube.com/watch?v=2mjfI0FYP7Y&feature=youtu.be