简体   繁体   English

"如何为 Google Cloud Functions 删除 tmpfs 或 \/tmp 目录中的文件?"

[英]How to delete files in tmpfs or /tmp directory for Google Cloud Functions?

I have a google cloud function I've written in Node.js which I have set to execute every 4 hours using the cloud scheduler.我有一个我用 Node.js 编写的谷歌云功能,我已经使用云调度程序设置为每 4 小时执行一次。 Basically the function populates a table I have in BigQuery.基本上,该函数填充了我在 BigQuery 中的一个表。 My function doesn't explicitly write anything to the tmp directory, it just stores things in local variables for streaming insertion into BigQuery like so:我的函数没有显式地向 tmp 目录写入任何内容,它只是将内容存储在局部变量中,以便像这样流式插入 BigQuery:

var rows = []

// code which fills the rows array

await bigqueryClient
      .dataset(datasetId)
      .table(tableId)
      .insert(rows)

Your code will delete all files the next<\/strong> time it runs, but if you created a file with something like const ws = fs.createWriteStream('\/tmp\/${fileName}');<\/code>您的代码将在下次<\/strong>运行时删除所有文件,但如果您创建了一个类似const ws = fs.createWriteStream('\/tmp\/${fileName}');<\/code> , the file will not be deleted until the next run. ,直到下次运行该文件才会被删除。

If you want to delete all files as part of the current process, then you can separate the part that creates a file(s) from the file cleanup and wrap both in a Promise<\/code> .如果要将所有文件作为当前进程的一部分删除,则可以将创建文件的部分与文件清理分开并将两者包装在Promise<\/code>中。

This will delete all files in \/tmp<\/code> .这将删除\/tmp<\/code>中的所有文件。

const directory = '/tmp';
const fileName  = `test_file_1.gz`;
 
function doSomething() {
  return new Promise((resolve) => {   
    const ws = fs.createWriteStream(`/tmp/${fileName}`);
    resolve();
  });
}

function fileCleanup() {
  return new Promise((resolve) => {   
    fs.readdir(directory, (err, files) => {
      if (err) throw err;
      console.log(files);

      for (const file of files) {
        fs.unlink(path.join(directory, file), err => {
          if (err) throw err;
          console.log(`${file} was deleted`);
        });
      }
    });
    resolve();
  });
}

doSomething().then(() => { fileCleanup(); }).then(() => { res.status(200).send('OK'); }).catch((err) => { throw new Error(err); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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