Minel Aydın
Minel Aydın

Reputation: 137

How to delete all json files within directory NodeJs

I need to delete only the json files within a directory (multiple levels). I'd hazard a guess that it's possible with fs-unlinkSync(path)

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

I was hoping to solve it with the following... fs.unlinkSync('./desktop/directory/*.json') but unfortunately the asterisk wouldn't select all. Any suggestion please?

Upvotes: 2

Views: 1604

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

You can list files using fs.readdirSync, then call fs.unlinkSync to delete. This can be called recursively to traverse an entire tree.

const fs = require("fs");
const path = require("path");

function deleteRecursively(dir, pattern) {
    let files = fs.readdirSync(dir).map(file => path.join(dir, file));
    for(let file of files) {
        const stat = fs.statSync(file);
        if (stat.isDirectory()) {
            deleteRecursively(file, pattern);
        } else {
            if (pattern.test(file)) {
                console.log(`Deleting file: ${file}...`);
                // Uncomment the next line once you're happy with the files being logged!
                try { 
                    //fs.unlinkSync(file);
                } catch (err) {
                    console.error(`An error occurred deleting file ${file}: ${err.message}`);
                } 
            }
        }
    }
}

deleteRecursively('./some_dir', /\.json$/);

I've actually left the line that deletes the file commented out.. I'd suggest you run the script and be happy the files that are logged are the right ones. Then just uncomment the fs.unlinkSync line to delete the files.

Upvotes: 5

Related Questions