Published on

How to get Random Temp File or Directory Path in Node


Sometime, we might just want to write/read a file temporarily.

Instead of us handling the file name and its path, we can instead use tempy package that takes care of those things for us. And it chooses the optimal path depending on your OS.

Let's get started by installing its dependency

npm install tempy
import {temporaryFile, temporaryDirectory} from 'tempy';

const tempFile = temporaryFile();

const tempFileWithExt = temporaryFile({extension: 'csv'});

const tempFileWithName = temporaryFile({name: 'hello.png'});

// Similarly for the directory
const directory =  temporaryDirectory();
const directoryWithPrefix = temporaryDirectory({prefix: 'name'});

Happy temporary files!