Node.js fs-extra emptyDir() Function
The fs-extra is a module that adds file system methods that are not included in the native fs module. It also adds promises support to the fs method. Some file system methods are not included in the native fs module, therefore, they have to be installed separately if we need to use them but the fs-extra module has all these methods available which makes it a great replacement for the fs module.
The emptyDir() function as the name suggests empty the whole directory. If any content is available in the directory it will be deleted by using this function. The directory itself is not deleted only the content present in the directory is deleted. If the directory does not exist, it is created.
- dir: It is a string that contains the path of the directory which will be emptied.
- callback: It is a function that will be called when the directory will become empty. It is an optional parameter. We can also use promises instead of the callback function.
Return value: The function does not return anything.
Follow the steps to implement the function:
1. The module can be installed by using the following command:
npm install fs-extra
2. After the installation of the module you can check the version of the installed module by using this command:
npm ls fs-extra
3. Create a file with the name index.js and require the fs-extra module in the file using the following command:
const fs = require('fs-extra');
4. Create a folder with the name test and add some files to the folder. This is the folder we will be passing in the function.
5. To run the file write the following command in the terminal:
Project Structure: The project structure will look like this.
Example 1: Below example illustrate the fs-extra emptyDir() function.
Output: All the files present in the test folder are now deleted. So the test folder is now empty.
All files deleted from directory Successfully.
Example 2: Below example illustrate the fs-extra emptyDir() function.
Output: Again the test folder is now empty. So this is how emptyDir() function is used.
All files deleted Successfully