1

I need to delete only the txt files within a directory (multiple levels). I'd hazard a guess that it's possible with fs-extra... https://github.com/jprichardson/node-fs-extra

But I can't find a solution without specifying the individual file name.

I was hoping to solve it with the following...

fse.remove('./desktop/directory/*.txt')

but unfortunately the asterisk wouldn't select all... as I then could have done something like the following...

fse.remove('./desktop/directory/sub1/*.txt')
fse.remove('./desktop/directory/sub1/sub2/*.txt')
fse.remove('./desktop/directory/sub1/sub2/sub3/*.txt')
fse.remove('./desktop/directory/sub1/sub2/sub3/sub4/*.txt')

Not the cleanest I know... But it's all I've got.

Any help or suggestions on this would be appreciated. Thanks.

2 Answers2

1

What about this?

fse.remove('./desktop/directory/**/*.txt')

Adding ** means to include all sub-directories

Anas AL-zghoul
  • 465
  • 5
  • 14
  • Unfortunately not :/ I tried to remove this sample file but it didn't work. .......fse.remove('./desktop/directory/**/sample.txt') //didn't work.......... fse.remove('./desktop/directory/sub1/sample.txt') //worked – Evan Meredith-Davies Apr 09 '19 at 12:03
1

If you are using rimraf, You can try this.

const rimraf = require('rimraf');
rimraf.sync('**/*.txt');

rimraf accept glob as the first parameter.

If you want to use it asynchronously, you can even write

rimraf('**/*.txt', options, () => {
 console.log('deleted')
})

Though fs-extra uses rimraf internally to delete the file.

Shareef
  • 351
  • 4
  • 12