Node.js | fsPromises.mkdtemp() Method

The fsPromises.mkdtemp() method is an inbuilt method which creates a unique temporary directory and resolves the Promise with the created directory path.

Syntax:

fs.Promises.mkdtemp( prefix, options )

Parameters: The method accepts two parameters as mentioned above and described below:

  • prefix: It is a string that denotes the path of the file.
  • options: It is a string or an object.
    • encoding: It is a string and by default it’s value is utf8.

Return Value: It returns the Promise object which represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Example: A temporary directory can be created with the following code:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// fsPromises.mkdtemp() method 
const fs = require("fs");
  
const fsPromises = fs.promises;
const prefix = "temp";
  
fsPromises.mkdtemp(prefix,{ encoding: "utf8"})
.then((folder)=>{
    console.log("Temp folder created ", folder)
})
.catch((err)=>{
    console.log(err)
});
);

chevron_right


Output:

Temp folder created  tempoe5zc9

A unique directory name is generated by appending six random characters to the end of the provided prefix. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.

The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.

fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-'))
 .catch(console.error);

The fsPromises.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory /tmp, if the intention is to create a temporary directory within /tmp, the prefix must end with a trailing platform-specific path separator (require(‘path’).sep).

My Personal Notes arrow_drop_up

Stepping steps of my ownself

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.