【问题标题】:How to clean temporary files in Firebase Cloud Functions如何清理 Firebase Cloud Functions 中的临时文件
【发布时间】:2019-10-11 08:55:06
【问题描述】:

我正在尝试使用云功能处理两个具有相同名称的不同图像(这是不可交换的)。该函数被触发以仅处理一个图像,第二个图像也是如此。问题是我无法删除临时文件,因此无法保存第二张图像,因为它具有相同的路径和相同的名称。我使用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() 单个文件但不起作用。

【问题讨论】:

  • 我的团队也有同样的问题

标签: javascript node.js firebase google-cloud-functions


【解决方案1】:

fs.unlinkSync() 仅适用于单个文件。它不适用于整个目录。您在目录类型的文件上调用它,这是行不通的。

您有很多选项可以删除整个目录。这个问题列出了您的一些选项:Remove directory which is not empty

【讨论】:

  • 我什至尝试使用单个文件,正如我在最后一行中所写的,但这也不起作用......
【解决方案2】:

为什么不使用 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?
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 2018-01-02
    • 2017-11-03
    • 2013-04-14
    • 1970-01-01
    • 2020-01-12
    • 2016-11-13
    • 2021-08-21
    相关资源
    最近更新 更多