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

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.

This question is related to javascript node.js

The answer is


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.


How about run a command line:

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

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

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


graph-fs


Install

npm i graph-fs

Use

const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");

directory.clear(); // <--