Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a tmp dir in node without collisions

I have a need a create a temporary "scratch" directory on-demand in node.js. The requirements are:

  • the dirname should be randomized (i.e. /tmp/aDIge4G/
  • the directory will be created within /tmp which may already have other randomly named directories.
  • if the directory already exists, I should throw rather than use it and overwrite someone else's work
  • this needs to be safe in a concurrent environment. I can't just check if the directory exists and then create it if it doesn't because someone else may have created a directory with the same name after I checked.

In other words, I need the answer to this question but for directories, not files.

This answer says that what I want to do can be accomplished by mkdir -p, but Node doesn't have the -p flag for fs.mkdir

like image 555
BonsaiOak Avatar asked Mar 01 '16 21:03

BonsaiOak


People also ask

How do I create a temp file in node?

var tmp = require('tmp'); var tmpObj = tmp. fileSync({ mode: 0644, prefix: 'projectA-', postfix: '. txt' }); console. log("File: ", tmpObj.name); console.

How do I create a temporary working directory?

Use mktemp -d . It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

What is $Tmpdir?

TMPDIR is the canonical environment variable in Unix and POSIX that should be used to specify a temporary directory for scratch space. Most Unix programs will honor this setting and use its value to denote the scratch area for temporary files instead of the common default of /tmp or /var/tmp.


1 Answers

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 
like image 153
Hettomei Avatar answered Sep 28 '22 18:09

Hettomei