Published on

How to get Resolved Temporary Directory Path in Node.js


Node.js has built-in functions using which you can get the temporary directory.

Here's how to do it.

import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';

const tempDirPath = os.tmpdir()
// eg: /var/folders/p0/0jn4_3xn5hs02w0jq5v77ymh0000gp/T

const resolvedTempDirPath = fs.realpathSync(tempDirPath);
// eg: /private/var/folders/p0/0jn4_3xn5hs02w0jq5v77ymh0000gp/T

How it works?

  • os.tmpdir() 👉 It returns the OS's temp path.
  • fs.realpathSync 👉 It is used to get the resolved path (meaning, it'll handle things like resolving symlink, relative path, etc)

Checkout tempy using which you can perform a lot of useful things with temporary directory/file

Happy temporary files!