8

I need to delete all files in a directory except for one that I have the name of. Let's say:

fs.unlink('./all except specialfile.txt', (err)) => { if (err) throw err; console.log('file deleted!'); } 
1
  • You'll probably need to read the list of files in the dir, then one at a time delete each, excluding your special file of course. Commented Apr 24, 2019 at 10:03

1 Answer 1

13

You have to get all files in the directory and then compare the name and delete the file if file name does not match your file

const fs = require('fs'); const path = require('path'); fs.readdir('./', (err, files) => { if (err) { console.log(err); } files.forEach(file => { const fileDir = path.join('./', file); if (file !== 'specialfile.txt') { fs.unlinkSync(fileDir); } }); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.