Is there a recommended way to remove temporary directories and files? #14715
-
Hi, I was wondering when and how it is sensible to manually remove temporary directories that are only required while a process is running. Initially, I was using the unload event to remove all directories after the process had successfully completed – const tempPath = await Deno.makeTempDir();
globalThis.onunload = (e: Event): void => {
Deno.remove(tempPath , { recursive: true });
}; However, the function is never called and the directory remains when the process terminates due to an exception. So, for the time being, I'm removing any old directories from previous runs at the start of the process. Similar to this – const tempPath = await Deno.makeTempDir({ prefix: `my-prefix-` });
for await (const dirEntry of Deno.readDir(path.resolve(tempPath, `../`))) {
if (!dirEntry.name.startsWith(`my-prefix-`)) continue;
const olderPath = path.resolve(tempPath, `../${dirEntry.name}`);
if (tempPath != olderPath) {
Deno.remove(olderPath, { recursive: true });
}
} Are there recommended methods for doing this with Deno? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Normally you should remove them right after using them in a const tempPath = await Deno.makeTempDir({ prefix: `my-prefix-` });
try {
// code that uses `tempPath`...
} finally {
await Deno.remove(tempPath, { recursive: true });
} |
Beta Was this translation helpful? Give feedback.
-
What exception are you seeing? Your first code snippet runs on my machine. |
Beta Was this translation helpful? Give feedback.
Normally you should remove them right after using them in a
finally
block: