How to create a tmp dir in node without collisions How to create a tmp dir in node without collisions node.js node.js

How to create a tmp dir in node without collisions


The current node api propose to create a temporary folder : https://nodejs.org/api/fs.html#fs_fs_mkdtemp_prefix_options_callback

which gives :

fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, folder) => {  if (err) throw err;  console.log(folder);  // Prints: /tmp/foo-itXde2});// folder /tmp/foo-itXde2 has been created on the file system


You can try package "tmp". It has a configuration parameter "template" which in turn uses Linux's mkstemp function which probably solves all your requirements.


A simple way to create unique directories would be using universally unique identifiers (UUIDs) within the path name.

Here is an example using pure-uuid:

const fs = require('fs-extra');const path = require('path');const UUID = require('pure-uuid');const id = new UUID(4).format();const directory = path.join('.', 'temp', id);fs.mkdirs(directory).then(() => {  console.log(`Created directory: ${directory}`);});

You will get an output like this:

Created directory: temp\165df8b8-18cd-4151-84ca-d763e2301e14

Note: In the code above I am using fs-extra as a drop-in replacement for fs, so you don't have to care about mkdir -p because fs-extra will create the directory and any necessary subdirectories.

Tip: If you want to save your directories within the operation system's default temp directory, then you can make use of os.tmpdir(). Here's an example of how this works:

const fs = require('fs-extra');const os = require('os');const path = require('path');const UUID = require('pure-uuid');const id = new UUID(4).format();const directory = path.join(os.tmpdir(), id);fs.mkdirs(directory).then(() => {  console.log(`Created directory: ${directory}`);});

Created directory: C:\Users\bennyn\AppData\Local\Temp\057a9978-4fd7-43d9-b5ea-db169f222dba