Unlink particular extension file in Js

I want to make a function which help if files/ directory haves .pdf / .doc / .jpeg /.png files it would be deleted otherwise, rest of the file will not be disturbed or deleted.
below in my function, it deletes all files except one readMe.txt [important file*] sweat_smile:
Please help me with how I do some modifications below code which help delete all the above-mentioned file extensions except file name readMe.txt

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

fs.readdir("./files/", (err, files) => {
	if (err) {
		console.log(err);
	}
	files.forEach((file) => {
		const fileDir = path.join("./files/", file);
		if (file !== "readMe.txt") {
			fs.unlinkSync(fileDir);
		}
	});
});

Maybe try something like this…

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

fs.readdir("./files/", (err, files) => {
	if (err) {
		console.log(err);
	}

    const extensions = ['.pdf', '.doc', '.jpeg', '.png'];

	files.forEach((file) => {
		const fileDir = path.join("./files/", file);
        // Get the extension name of the file, lowercase it, then see if it is in the array of extensions
        // defined above. If so, remove it.
		if (extensions.includes(path.extname(file).toLowerCase())) {
			fs.unlinkSync(fileDir);
		}
	});
});

If you are unfamiliar with what I am doing here, look up arrays, the path.extname() method and the includes method of arrays. :slight_smile:

1 Like