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

18 Jul, 2020
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.777recursive: It is a boolean value which specifies whether parent directories should be created or not. By default its value is false.
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
// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util')  // Convert callback based methods to promise// based methodsconst makeDir = util.promisify(fs.mkdir)const readDir = util.promisify(fs.readdir)  // Create new directorymakeDir(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 moduleconst fs = require('fs')const util = require('util')  // Convert callback based methods to promise// based methodsconst 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 moduleconst fs = require('fs')const util = require('util')  // Convert callback based methods to // promise based methodsconst 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 directorymakeDir('./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 moduleconst fs = require('fs')const util = require('util')  // Convert callback based methods to promise// based methodsconst 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:
Node.js-fs-module
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React