Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/35733684/how-to-create-a-tmp-dir-in-node-without-collisions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...