javascriptnode.jspackage.jsonrmnode.js-fs

node js rimraf delete dist folder in any of the subfolders of src


I have many dist folders inside src folder. It can be nested at any depth.

src
    - dist
    - main
        - dist
        - com
            - dist
            ....
    - test
        - dist
        - com
            - dist

I need a command in rimraf to delete all such dist folders inside src folder.

I tried rimraf src/**/dist, src/*/dist, src/**/*/dist, but none of them are working, in fact I am getting an error saying Error: Illegal characters in path.

If its not possible to do this with rimraf, is there any other simpler solution using node js? The tedious solution might be to write my own script to call rimraf recursively after I get directory structure using fs or something.


Solution

  • You should be able to use the --glob flag:

    rimraf src/*/dist --glob
    

    Use case

    Here is a basic init.js file to get the folder structure set up:

    import * as fs from 'fs/promises';
    
    await fs.mkdir('src/main/dist', { recursive: true });
    await fs.mkdir('src/main/com/dist', { recursive: true });
    await fs.mkdir('test/dist', { recursive: true });
    await fs.mkdir('test/com/dist', { recursive: true });
    
    console.log('Done...'); // Created all directories
    

    And here is the clean.js:

    import { rimraf } from 'rimraf';
    
    // rimraf src/*/dist --glob
    await rimraf('src/*/dist', { glob: true });
    
    console.log("Done..."); // Removed all dist/ (sub)directories