How to operate callback-based fs.mkdir() method with promises in Node.js ?

The fs.mkdir() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The mkdir() method is used to asynchronously create a directory.

The fs.mkdir() method is based on callback. Using callback methods leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way.

Syntax:

fs.mkdir(path, options)

Note: Callback not required since we operate the method with promises.

Parameters: This method accept two parameters as mentioned above and described below:



  • path: It is a String, Buffer or URL that specifies the path to the directory that has to be created.
  • options: It is an optional parameter which affects the output in someway accordingly we provide it to the function call or not.
    • mode: It is a string or an integer which used to set the directory permission. By default its value is 0.777
    • recursive: It is a boolean value which specifies whether parent directories should be created or not. By default its value is false.

Approach: The fs.mkdir() method based on callback. To operate it with promises, first, we use promisify() method defined in utilities module to convert it into a promise based method.

Example 1: Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to promise
// based methods
const makeDir = util.promisify(fs.mkdir)
const readDir = util.promisify(fs.readdir)
  
// Create new directory
makeDir(dir='./Test Directory')
.then(() => {
  console.log(`Directory '${dir}' is created`)
})
  
// If promise gets rejected
.catch(err => {
    console.log(`Error occurs, 
    Error code -> ${err.code},
    Error No -> ${err.errno}`);
})

chevron_right


Implementing the same functionality using async await:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to promise
// based methods
const makeDir = util.promisify(fs.mkdir)
const readDir = util.promisify(fs.readdir)
  
const createDirectory = async path => {
  await makeDir(path)
  console.log(`Directory '${path}' is created`)
}
  
createDirectory('./TestDirectory')
  
// If promise gets rejected
.catch(err => {
    console.log(`Error occurs, 
    Error code -> ${err.code},
    Error No -> ${err.errno}`);
})

chevron_right


Run the index.js file using the following command:

node index.js

File contents before running the program :

File contents after running the program:

Output:

Directory './Test Directory' is created

Example 2: Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const makeDir = util.promisify(fs.mkdir)
const readDir = util.promisify(fs.readdir)
  
console.log(`\nBefore creating new Directory : \n`)
readDir(process.cwd())
.then(filenames => {
  
   // Fetch the contents of current working
   // directory before creating new directory
   for(let filename of filenames){
      console.log(filename)
   }
})
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code},
   Error No -> ${err.errno}`);
})
  
// Create new directory
makeDir('./Test Directory')
.then(() => {
  
   // Fetch the contents of current working
   // directory after creating new directory
   console.log(`\nAfter creating new directory : \n`)
     
   return readDir(process.cwd())
})
  
.then(filenames => {
  for(let filename of filenames) {
    console.log(filename)
  }
})
  
// If promise gets rejected
.catch(err => {
  console.log(`Error occurs, 
  Error code -> ${err.code},
  Error No -> ${err.errno}`)
})

chevron_right


Implementing same functionality using async await:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to promise
// based methods
const makeDir = util.promisify(fs.mkdir)
const readDir = util.promisify(fs.readdir)
  
const createDirectory = async path => {
  console.log(`\nBefore creating new Directory : \n`)
    
  // Fetch the contents of current working directory
  // before creating new directory
  const oldContents = await readDir(process.cwd())  
  for(let filename of oldContents) {
    console.log(filename)
  }
  
  // Create new directory
  await makeDir('./Test Directory')
  console.log(`\nAfter creating new directory : \n`)
  
  // Fetch the contents of current working directory
  // after creating new directory
  const newContents = await readDir(process.cwd())
  for(let filename of newContents) {
    console.log(filename)
  }
}
  
createDirectory('./TestDirectory')
// If promise gets rejected
.catch(err => {
   console.log(`Error occurs, 
   Error code -> ${err.code},
   Error No -> ${err.errno}`);
});

chevron_right


Run the index.js file using the following command:

node index.js

File contents before running the program:

File contents after running the program:

Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.