Delete all files and folder except

Viewed 31

My function is:

function Delete(dir){
    log(`[DELETE] ${dir}.`)
    fs.readdir(dir, (err, files) => {
    if (err) {
        console.log(err);
    }

    files.forEach(file => {
        const fileDir = path.join(dir, file);

        if (file !== 'specialfile.txt') {
           fs.rm(fileDir, { recursive:true }, (err) => {
        if(err){
        // File deletion failed
        console.error(err.message);
        return;
        }
        })
        }
    });
});

But he only preserves the "specialfile.txt" not the content file in case i like preserver a list of files inside in "specialfile.txt".

specialfile.txt:

error.dll
Windows.txt
jose.cfg

i need exclude all files and folder except this file content;

1 Answers

try using fs.unlink. fs.unlink will not work on a directory, empty or otherwise.

fs.unlink('path/file.txt', (err) => {
   if(err) throw new Error(err);
   console.log('file is deleted.');
}
Related