Deno nuggets: Get OS temporary directory
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to get OS temporary directory path in Deno?
/tmp
/var/tmp
/var/folders/k0/3447gbp16vl309gg50ygclwr0000gn/T
The OS temporary directory is a useful place to host temporary (short-lived) files, directories, etc.
Solution
Imports
No imports are required.
Getting temporary directory
Deno doesn’t provide a direct way to get OS temporary directory. Therefore, the temporary path need to searched in the following order (move to next step only if previous step yields nothing):
- Environment variable: TMPDIR
- Environment variable: TMP
- Environment variable: TEMP
- /tmp
The above should work on all the platforms. Here is a one liner function that implements the above algorithm:
const getOSTempDir = () => Deno.env.get('TMPDIR') || Deno.env.get('TMP') || Deno.env.get('TEMP') || '/tmp';getOSTempDir();
On Mac: /var/folders/k0/3447gbp16vl309gg50ygclwr0000gn/T
On Centos: /tmp
As OS temporary directory path is a global setting that is not going to change, it might also be useful to include the temporary directory path in Deno namespace. To add to global namespace, type checking needs to be disabled using — no-check.
Object.defineProperty(Deno, "tempDir", {value: Deno.env.get('TMPDIR') || Deno.env.get('TMP') || Deno.env.get('TEMP') || '/tmp', enumerable: true});Deno.tempDir;
/var/folders/k0/3447gbp16vl309gg50ygclwr0000gn/T/
This story is a part of the exclusive medium publication on Deno: Deno World.