Delete all file in folder nodejs

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.

Delete all file in folder nodejs

asked Nov 22, 2014 at 0:58

youbetternotyoubetternot

2,3262 gold badges15 silver badges18 bronze badges

3

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

answered Feb 11, 2017 at 23:23

7

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.

Delete all file in folder nodejs

answered Feb 27, 2019 at 11:03

Delete all file in folder nodejs

Samiul AlamSamiul Alam

1,8943 gold badges9 silver badges27 bronze badges

3

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

answered Mar 6, 2018 at 7:37

Nicolas GuérinetNicolas Guérinet

1,9681 gold badge26 silver badges35 bronze badges

2

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

answered Dec 16, 2021 at 22:29

JeffD23JeffD23

7,4861 gold badge27 silver badges40 bronze badges

3

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

answered Mar 22, 2018 at 5:15

Jason KimJason Kim

17.1k13 gold badges65 silver badges104 bronze badges

3

How about run a command line:

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

answered Jan 29, 2021 at 7:48

Rudy HuynhRudy Huynh

4804 silver badges10 bronze badges

1

Short vanilla Node 10 solution

import fs from 'fs/promises'

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

answered Sep 16, 2021 at 12:04

4

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)

answered Aug 30, 2021 at 7:27

Delete all file in folder nodejs

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

answered Mar 3 at 6:45

Delete all file in folder nodejs

SridharKrithaSridharKritha

7,1372 gold badges43 silver badges40 bronze badges

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.

answered Jun 28 at 21:47

electrovirelectrovir

7701 gold badge16 silver badges19 bronze badges

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

answered Nov 19, 2021 at 5:21

wazwaz

1,04615 silver badges30 bronze badges

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.

answered Sep 3 at 19:28

Delete all file in folder nodejs

GroguGrogu

1,67713 silver badges24 bronze badges

❄️ You can use graph-fs ↗️

directory.clear() // empties it

answered Feb 18 at 14:18

Delete all file in folder nodejs

YairoproYairopro

7,5005 gold badges37 silver badges48 bronze badges

2

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

});

answered Jul 6 at 9:14

Delete all file in folder nodejs

How do you delete all files in node JS?

Node JS - How to Delete All Files in Directory?.
Step 1: Create Node App. run bellow command and create node app. mkdir my-app. cd my-app. npm init..
Step 2: Create server.js file. Make sure, you have created "images" folder with some images. server.js. const fs = require('fs'); var folder = './images/';.

How do I empty a folder in node?

How to Delete a File or Directory in Node..
Removing FIles. Using fsPromises.unlink() with async/await. Using fs.unlink() and fs.unlinkSync().
Removing Directories. Using fsPromises.rmdir() with async/await. Using fs.rm() and fs.rmSync().

How do I delete everything in a folder?

You can delete multiple files or folders by holding down the Ctrl key and clicking each file or folder before pressing Delete . You can hold down the Shift key while pressing the Delete key to prevent files from going to the Recycle Bin when deleted.

Which of the following is the correct approach to solve the process out of memory exception error in Nodejs?

This exception can be solved by increasing the default memory allocated to our program to the required memory by using the following command. Parameters: SPACE_REQD: Pass the increased memory space (in Megabytes).

Tải thêm tài liệu liên quan đến bài viết Delete all file in folder nodejs