簡體   English   中英

如何清除Firebase Cloud Functions中的臨時文件

[英]How to clean temporary files in Firebase Cloud Functions

我正在嘗試使用雲函數處理具有相同名稱(並且這是不可交換的)的兩個不同圖像。 觸發該功能以僅處理圖像,第二個圖像也發生相同的情況。 問題是我無法刪除臨時文件,因此第二張圖像無法保存,因為它具有相同的路徑和名稱。 我使用fs.unlinkSync()清除臨時文件夾,但這不起作用。 這是代碼:

exports.thumb= functions.database.ref('/{uid}/upload')

.onUpdate(async (change, context) => {


const fileName = "RawImage.jpg";
const userId = context.auth.uid;
const bucket = storage.bucket("-----");
const workingDir = path.join(os.tmpdir(), "thumbs");
const tempFilePath = path.join(workingDir, fileName);
const filePath = path.join(userId,fileName);

await fs.ensureDir(workingDir);

await bucket.file(filePath).download({destination: tempFilePath});

const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = path.join(userId, thumbFileName);
const out = path.join(workingDir, thumbFileName);


const uploadPromises = async () => {

  await sharp(tempFilePath)
        .resize(300, 200)
        .grayscale()
        .toFile(out);

  return await bucket.upload(out, {
            destination: thumbFilePath,
        });

  }

    const v = await uploadPromises();


    return fs.unlinkSync(workingDir);

  });

最后一行被分配以清除存儲臨時文件的工作目錄,但是該目錄不起作用(處理第二個映像,始終返回第一個映像)。 我什至嘗試fs.unlincSync()文件,但不起作用。

fs.unlinkSync()僅適用於單個文件。 它不適用於整個目錄。 您在文件的目錄類型上調用它,但這將無法正常工作。

您有很多刪除整個目錄的選項。 這個問題列出了您的一些選項: 刪除不為空的目錄

為什么不使用fs.remove(out)而不是fs.unlinkSync(workingDir)? 我假設您正在使用https://www.npmjs.com/package/fs-extra

onUpdateCallback(change, context) {
    ... // The other code
    const out = path.join(workingDir, thumbFileName);

    const uploadPromises = async () => {
        await sharp(tempFilePath).resize(300, 200).grayscale().toFile(out);

        return await bucket.upload(out, {destination: thumbFilePath});
    }

    const v = await uploadPromises();
    // return fs.unlinkSync(workingDir);
    return fs.remove(out); // Why not this instead?
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM