EN VI

Node.js - How to delete the subfolders and files inside the subfolders, but not deleting the root files in nodejs?

2024-03-11 04:30:05
Node.js - How to delete the subfolders and files inside the subfolders, but not deleting the root files in nodejs

consider I have a folder

Parent

  • one.json
  • two.json
  • folder1 -- one.java -- two.java
  • folder2 -- three.java

Now, I need to delete the folder1 and folder 2, but should not delete one.json and two.json. Basically all the files in the root should exist nd all folders and its contents should get deleted. How we can do it in nodejs. Please help

Solution:

Assuming the path to the parent directory (ie the one containing one.json, two.json and folder1 and folder2) is /path/to/parent. Furthermore I assume you are familiar with the promises api of the node fs/promises module

Then you can use readdir to get all entries of your parent directory

import { readdir } from 'node:fs/promises';
let entries = await readdir('/path/to/parent', { withFileTypes: true }); 

Setting withFileTypes to true will return a list of of fs.Dirent objects. Then you can iterate over that list of entries, and whenever one of them is a directory (ie entry.isDirectory() returns true) you delete this directory using fs.rmdir and leave all other entries untouched

import { rmdir } from 'node:fs/promises';
import { join } from 'path';

for (let entry of entries) {
  if (!entry.isDirectory())
    continue;

  await rmdir(join(entry.parentPath, entry.name), { recursive: true });
}

Using recursive: true with rmdir will delete all elements in the specified directory and finally the directory itself. If you don't specify recursive: true, you can only remove empty directories.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login