How to remove all files from directory without removing directory in Node.js
Yes, there is a module fs-extra. There is a method .emptyDir()
inside this module which does the job. Here is an example:
// NON-ES6 EXAMPLE
const fsExtra = require('fs-extra');
fsExtra.emptyDirSync(fileDir);
// ES6 EXAMPLE
import * as fsExtra from "fs-extra";
fsExtra.emptyDirSync(fileDir);
There is also an asynchronous version of this module too. Anyone can check out the link.
To remove all files from a directory, first you need to list all files in the directory using fs.readdir
, then you can use fs.unlink
to remove each file. Also fs.readdir
will give just the file names, you need to concat with the directory name to get the full path.
Here is an example
const fs = require('fs');
const path = require('path');
const directory = 'test';
fs.readdir(directory, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(directory, file), err => {
if (err) throw err;
});
}
});
There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.
Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.
const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });
https://www.npmjs.com/package/rimraf