This content originally appeared on DEV Community and was authored by Ethan
Hello! I had to delete all directories that were in a directory called "files", just thought I'd share the solution. 😃
const { rmSync, promises: { readdir } } = require('fs');
(async () => {
try {
const fileNames = await readdir('./files');
for (const fileName of fileNames) {
console.log(`deleting file with name ${fileName}`);
rmSync(`./files/${fileName}`, { recursive: true });
}
} catch (error) {
console.error('failed to delete directories', error);
}
})();
Short and sweet. 😎
What this basically does is read all the directories under the directory called "files" and puts them into an array of file names using the readdir function.
Then it loops through the names of the directories and deletes them using rmSync.
Also it's very important to handle errors with nodejs as an unexpected error may kill the application. 🥲
If you have a better, cleaner solution then please share. This is how I handled it. 🙂
Like me work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee.
This content originally appeared on DEV Community and was authored by Ethan
Ethan | Sciencx (2022-03-18T02:43:49+00:00) Deleting multiple directories with Nodejs/Javascript. Retrieved from https://www.scien.cx/2022/03/18/deleting-multiple-directories-with-nodejs-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.