EmptyDir() function in fs-extra - NodeJS

Node.jsServer Side ProgrammingProgramming

Introduction to Async emptyDir()

This method is used to empty a directory whether it is empty or not. If the directory is not empty it will remove all its contents and empty it. A new empty directory is created if the directory does not exist.

Syntax

emptyDir(dir, [, callbacks])

Parameters

  • dir – This is a string paramter which will hold the location of the directory structure.

  • callback – This function will give a callback if any error occurs.

Example 1

  • Check that fs-extra is installed before proceeding; if not, install fs-exra.

  • You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
  • Create a asyncEmptyDir.js and copy-paste the following code snippet into that file.

  • Now, run the following command to run the following code snippet.

node asyncEmptyDir.js

Code Snippet

const fs = require('fs-extra')

// Assuming the directory exists and has content
// Checking directory with a callback:
fs.emptyDir('/tmp/dir', err => {
   if (err) return console.error(err)
   console.log('Async Success with callback !')
})

// Checking directory with Promises:
fs.emptyDir('/tmp/dir')
.then(() => {
   console.log('Async Success with Promises !')
})
.catch(err => {
   console.error(err)
})

// Checking directory with async/await
async function asyncEmptyDir () {
   try {
      await fs.emptyDir('/tmp/dir')
      console.log('Await Success !')
   } catch (err) {
      console.error(err)
   }
}
asyncEmptyDir()

Output

C:\Users\tutorialsPoint\> node asyncEmptyDir.js
Async Success with callback !
Async Success with Promises !
Await Success !
raja
Published on 27-Apr-2021 09:35:40
Advertisements