简体   繁体   中英

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.

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

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.

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

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

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

如何运行命令行:

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

Short vanilla Node 10 solution

import fs from 'fs/promises'

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

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)

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

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

Yet another alternative:

import {mkdir, rm} from 'fs/promises';

async function clearDirectory(dirPath) {
    await rm(dirPath, {recursive: true});
    await mkdir(dirPath);
}

This is actually deleting the directory entirely (with rm ) but then immediately recreating it so it looks like it was merely emptied out. This will affect folder metadata and possibly ownership, so it will not work in all use cases.

🚀 graph-fs


Install

npm i graph-fs

Use

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

directory.clear(); // <--

❄️你可以使用graph-fs ↗️

directory.clear() // empties it

This can be done with vanilla nodejs dependencies:

const fs = require('fs');
const dir = 'www/foldertoempty';

fs.readdirSync(dir).forEach(f=>fs.rmdirSync(

`${dir}/${f}`,
{
recursive : true,
force : true 
}
));

Adding recursive and force makes sure that non-empty folders get deleted as well.

const fs = require();

fs.readdir('test', (err, files) => {
    if (err) throw err;
    for (let file of files) 
        fs.unlink('./test/' + file, (err) => {
            if (err) throw err;
        });

    return fs.rmdir('test', (err) => {
        if (err) throw err;
        console.log('folder is deleted');
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM