Node.js fs-extra emptyDirSync() Function
Last Updated :
04 Apr, 2023
The emptyDirSync() function is the synchronous version of the emptyDir() function. The function ensures that the given directory is empty. If the directory is not empty, it will delete all the content present in that directory. The directory itself is not deleted. If the directory does not exist, it will be created by the function itself.
Syntax:
fs.emptyDirSync(dir)
// OR
fs.emptydirSync(dir)
Parameters: This function accepts the following parameter:
- dir: It is a string that contains the path of the directory.
Return value: The function does not return anything.
Follow the steps to implement the function:
Step 1: The module can be installed by using the following command:
npm install fs-extra
Step 2: After the installation of the module you can check the version of the installed module by using this command:
npm ls fs-extra
Step 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');
Step 4: To run the file write the following command in the terminal:
node index.js
Project Structure: The project structure will look like this.
Example 1:
Filename: index.js
Javascript
const fs = require( "fs-extra" );
const numberOfFiles = (dir) => {
const noOfFiles = fs.readdirSync(dir);
return noOfFiles.length;
};
let dir = "dir" ;
let before = numberOfFiles(dir);
console.log(
`Number of files in directory before calling the function : ${before}`
);
fs.emptyDirSync(dir);
const after = numberOfFiles(dir);
console.log(`Number of files in directory after` +
` calling the function : ${after}`);
console.log( "Directory is empty now" );
|
Run the index.js file using the following command:
node index.js
Output:
Number of files in directory before calling the function: 2
Number of files in directory after calling the function: 0
Directory is empty now
Example 2:
Filename: index.js
Javascript
const fs = require( "fs-extra" );
let numberOfFiles = (dir) => {
let noOfFiles = fs.readdirSync(dir);
return noOfFiles.length;
};
const dir = "dir/direc" ;
const before = numberOfFiles(dir);
console.log(
`Number of files in directory before calling the function : ${before}`
);
fs.emptyDirSync(dir);
const after = numberOfFiles(dir);
console.log(`Number of files in directory after` +
` calling the function : ${after}`);
console.log( "Directory is empty now" );
|
Run the index.js file using the following command:
node index.js
Output:
Number of files in directory before calling the function: 1
Number of files in directory after calling the function: 0
Directory is empty now
Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/emptyDir-sync.md
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...