How to delete all json files within directory NodeJs How to delete all json files within directory NodeJs express express

How to delete all json files within directory NodeJs


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.