json file automatic delete in nodejs issue code example

Example: how to delete all json files in a directory nodejs

// delete all json files in same directory as nodejs script, or subdirectory.

const directoryPath = path.join(__dirname, "sub_directory_if_needed");

function DeleteFiles() {
    //passsing directoryPath and callback function
    fs.readdir(directoryPath, function (err, files) {
        //handling error
        if (err) {
            return console.log('Unable to scan directory: ' + err);
        } 
        //listing all files using forEach
        files.forEach(function (file) {
            // Do whatever you want to do with the file
            if (file !== "package.json") { // Making sure not to delete package.json, as it should not be deleted
                if (file.endsWith(".json")) {
                    fs.unlink(`${directoryPath}/${file}`, function(err) {
                        if (err) throw err
                        console.log(file, "deleted")
                    })
                }
            }
        });
    });
}

DeleteFiles()