Answers for "nodejs fs delete directory files and folders"

0

delete dir nodejs

fs.rmdirSync(dir, { recursive: true });
Posted by: Guest on August-06-2020
1

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()
Posted by: Guest on August-05-2020

Code answers related to "nodejs fs delete directory files and folders"

Code answers related to "Javascript"

Browse Popular Code Answers by Language