How to remove all files from directory without removing directory in Node.js

Javascriptnode.js

Javascript Problem Overview


How to remove all files from a directory without removing a directory itself using Node.js?
I want to remove temporary files. I am not any good with filesystems yet.

I have found this method, which will remove files and the directory. In that, something like /path/to/directory/* won't work.

I don't really know what commands should use. Thanks for the help.

Javascript Solutions


Solution 1 - Javascript

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;
    });
  }
});

Solution 2 - Javascript

Yes, there is a module fs-extra. There is a method .emptyDir() inside this module which does the job. Here is an example:

const fsExtra = require('fs-extra')

fsExtra.emptyDirSync(fileDir)

There is also an asynchronous version of this module too. Anyone can check out the link.

Solution 3 - Javascript

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

Solution 4 - Javascript

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

Solution 5 - Javascript

It can also be done with a synchronous one-liner without dependencies:

const { readdirSync, rmSync } = require('fs');
const dir = './dir/path';

readdirSync(dir).forEach(f => rmSync(`${dir}/${f}`));

Solution 6 - Javascript

How about run a command line:

require('child_process').execSync('rm -rf /path/to/directory/*')

Solution 7 - Javascript

Short vanilla Node 10 solution

import fs from 'fs/promises'

await fs.readdir('folder').then((f) => Promise.all(f.map(e => fs.unlink(e))))

Solution 8 - Javascript

Improvement on Rodrigo's answer, using async and promises

const fs = require('fs').promises;
const path = require('path');

const directory = 'test';

let files = [];
try{
   files = await fs.readdir(directory);
}
catch(e){
   throw e;
}

if(!files.length){
  return;
}

const promises = files.map(e => fs.unlink(path.join(directory, e)));
await Promise.all(promises)

Solution 9 - Javascript

Promise version of directory cleanup utility function:

const fs = require('fs').promises; // promise version of require('fs');

async function cleanDirectory(directory) {
	try {
		await fs.readdir(directory).then((files) => Promise.all(files.map(file => fs.unlink(`${directory}/${file}`))));
	} catch(err) {
		console.log(err);
	}
}

cleanDirectory("./somepath/myDir");

Solution 10 - Javascript

If you get this error:

[Error: ENOENT: no such file or directory, unlink 'filename.js'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'unlink',
  path: 'filename.js'
}

Add the folder path in

const folderPath = './Path/to/folder/'
await fs.promises.readdir(folderPath)
    .then((f) => Promise.all(f.map(e => fs.promises.unlink(`${folderPath}${e}`))))

Solution 11 - Javascript

❄️ You can use graph-fs ↗️
directory.clear() // empties it

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyoubetternotView Question on Stackoverflow
Solution 1 - JavascriptRodrigo5244View Answer on Stackoverflow
Solution 2 - JavascriptSamiul AlamView Answer on Stackoverflow
Solution 3 - JavascriptNicolas GuérinetView Answer on Stackoverflow
Solution 4 - JavascriptJason KimView Answer on Stackoverflow
Solution 5 - JavascriptJeffD23View Answer on Stackoverflow
Solution 6 - JavascriptRudy HuynhView Answer on Stackoverflow
Solution 7 - JavascriptAndreas TzionisView Answer on Stackoverflow
Solution 8 - JavascriptSethuraman SrinivasanView Answer on Stackoverflow
Solution 9 - JavascriptSridharKrithaView Answer on Stackoverflow
Solution 10 - JavascriptwazView Answer on Stackoverflow
Solution 11 - JavascriptYairoproView Answer on Stackoverflow