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.