Open In App

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:

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




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

Implementing the same functionality using async await:




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

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




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

Implementing same functionality using async await:




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

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:


Article Tags :