The JS runtimes
Published in

The JS runtimes

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store