Open In App

Node.js fsPromises.mkdtemp() Method

Last Updated : 08 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:




// 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)
});
);


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).


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads