node.jsfs-extra

How to delete all txt files within directory NodeJs


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.


Solution

  • 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.