简体   繁体   中英

How to clean temporary files in Firebase Cloud Functions

I'm trying to process two different images with the same name (and this is not exchangeable) with cloud functions. The function is triggered to process only a image and the same happend for the second image. The problem is I'm not able to delete temporary files, so the second image cannot be saved because it has the same path and the same name. I use fs.unlinkSync() to clear temp folder but this not works. This is the code:

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);

  });

The last line is assigned to clear the working directory where temp files are stored but this not work (processing the second image, returns always the first image). I tried even to fs.unlincSync() the sigle files but not works.

fs.unlinkSync() only works on individual files. It does not work on entire directories. You're calling it on a directory type of file, and that's not going to work.

You have a lot of options for deleting an entire directory. This question lists some of your options: Remove directory which is not empty

Why not do fs.remove(out) instead of fs.unlinkSync(workingDir) ? I'm assuming you're using 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?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM