To remove a directory or a folder, we can use the rmdirSync()
method from the fs
(filesystem) module Node.js. This will synchronously remove the directory.
// Remove directory synchronously
fs.rmdirSync("./FilesDirectory", { recursive: true });
console.log("Successfully deleted directory!");
For exampe let's consider a directory called FilesDirectory
like this,
// require fs module
const fs = require("fs");
// path
const path = "./FilesDirectory";
Now let's use the fs.rmdirSync()
function and
- pass the path as the first argument
- optional
options
object with a property ofrecursive
set to booleantrue
as the second argument. This is done so that any files or directories inside the directory are also deleted. If you don't want a directory with files not to be deleted, you can remove theoptions
object completely.
to the function like this,
// require fs module
const fs = require("fs");
// path
const path = "./FilesDirectory";
// remove directory by passing path
// as the first argument to the function
fs.rmdirSync(path, { recursive: true });
console.log("Successfully deleted directory!");
See this example live in repl.it.