798

How do I delete a file with node.js?

http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback

I don't see a remove command?

Ifnot
  • 4,914
  • 4
  • 33
  • 47
Mark
  • 32,293
  • 33
  • 107
  • 137

24 Answers24

1053

I think you want to use fs.unlink.

More info on fs can be found here.

Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51
Nick
  • 25,026
  • 7
  • 51
  • 83
341

You can call fs.unlink(path, callback) for Asynchronous unlink(2) or fs.unlinkSync(path) for Synchronous unlink(2).
Where path is file-path which you want to remove.

For example we want to remove discovery.docx file from c:/book directory. So my file-path is c:/book/discovery.docx. So code for removing that file will be,

var fs = require('fs');
var filePath = 'c:/book/discovery.docx'; 
fs.unlinkSync(filePath);
Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
sourcecode
  • 4,116
  • 1
  • 20
  • 14
91

If you want to check file before delete whether it exist or not. So, use fs.stat or fs.statSync (Synchronous) instead of fs.exists. Because according to the latest node.js documentation, fs.exists now deprecated.

For example:-

 fs.stat('./server/upload/my.csv', function (err, stats) {
   console.log(stats);//here we got all information of file in stats variable

   if (err) {
       return console.error(err);
   }

   fs.unlink('./server/upload/my.csv',function(err){
        if(err) return console.log(err);
        console.log('file deleted successfully');
   });  
});
Community
  • 1
  • 1
vineet
  • 13,832
  • 10
  • 56
  • 76
  • What if I check it exists, but it's blocked by another process - or, I check it exists, and it's fine, but then another process randomly blocks it before I'm able to delete. How can I block straight after checking? then wouldnt I not be able to delete as its blocked –  Oct 11 '16 at 15:40
  • 7
    Note that fs.exists() is deprecated, but fs.existsSync() is not. – Tim Jan 21 '17 at 16:14
  • 6
    There's a reason it's deprecated: often times you creates a race condition if you check that a file exists before deleting it. Instead, you should only call `fs.unlink`, and if the file doesn't exist, you'll have an `ENOENT` error in the callback. No need to check before trying to unlink. – ZachB Jul 25 '17 at 05:26
  • @ZachB why delete operation `fs.unlink` perform when file not existed, so my view is that check file before remove. – vineet Jul 25 '17 at 06:29
  • You shouldn't check if it exists if there are multiple threads or processes that might be using or trying to delete the same file, in which case your check that the file exists will become invalid between the time you check that it exists and the time you try to delete it. Just check for the ENOENT error code in the `unlink` callback. If that error occurred, the file didn't exist. Look at Searene's answer for example. – ZachB Jul 25 '17 at 11:37
  • 1
    The big problem with this approach is that it throws errors for non-exceptional cases. Major debugging a real PITA. Node should have taken a different approach, IMO. – nicodemus13 Mar 05 '20 at 10:16
55

I don't think you have to check if file exists or not, fs.unlink will check it for you.

fs.unlink('fileToBeRemoved', function(err) {
    if(err && err.code == 'ENOENT') {
        // file doens't exist
        console.info("File doesn't exist, won't remove it.");
    } else if (err) {
        // other errors, e.g. maybe we don't have enough permission
        console.error("Error occurred while trying to remove file");
    } else {
        console.info(`removed`);
    }
});
Searene
  • 25,920
  • 39
  • 129
  • 186
52

2020 Answer

With the release of node v14.14.0 you can now do.

fs.rmSync("path/to/file", {
    force: true,
});

https://nodejs.org/api/fs.html#fsrmsyncpath-options

Blake Plumb
  • 6,779
  • 3
  • 33
  • 54
  • 4
    The docs say force means: `force When true, exceptions will be ignored if path does not exist. Default: false.` – ccalvert May 15 '22 at 18:59
  • Jumping to this answer, it's missing some context. Need to add `var fs = require('fs');` to the beginning. – Michael Mar 20 '23 at 17:46
31

Here is a small snippet of I made for this purpose,

var fs = require('fs');
var gutil = require('gulp-util');

fs.exists('./www/index.html', function(exists) {
  if(exists) {
    //Show in green
    console.log(gutil.colors.green('File exists. Deleting now ...'));
    fs.unlink('./www/index.html');
  } else {
    //Show in red
    console.log(gutil.colors.red('File not found, so not deleting.'));
  }
});
Stranger
  • 10,332
  • 18
  • 78
  • 115
  • 4
    Async exists is deprecated https://nodejs.org/api/fs.html#fs_fs_exists_path_callback – Mirodinho Nov 09 '16 at 17:06
  • 3
    What if the file gets deleted by others after you check with `fs.exists` and before you remove it with `fs.unlink`? It could happen. – Searene Feb 20 '17 at 00:42
  • 4
    You should not check if a file exists before attempting to unlink it. Just call `unlink`, and if it doesn't exist, handle the `ENOENT` error. Otherwise you can create a race condition. – ZachB Jul 25 '17 at 05:28
23

2019 and Node 10+ is here. Below the version using sweet async/await way.

Now no need to wrap fs.unlink into Promises nor to use additional packages (like fs-extra) anymore.

Just use native fs Promises API.

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

(async () => {
  try {
    await fs.unlink('~/any/file');
  } catch (e) {
    // file doesn't exist, no permissions, etc..
    // full list of possible errors is here 
    // http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS
    console.log(e);
  }
})();

Here is fsPromises.unlink spec from Node docs.

Also please note that fs.promises API marked as experimental in Node 10.x.x (but works totally fine, though), and no longer experimental since 11.14.0.

Artyom Pranovich
  • 6,814
  • 8
  • 41
  • 60
16

You can do the following thing

const deleteFile = './docs/deleteme.txt'
if (fs.existsSync(deleteFile)) {
    fs.unlink(deleteFile, (err) => {
        if (err) {
            console.log(err);
        }
        console.log('deleted');
    })
}

Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.

fs.unlink() will not work on a directory, empty or otherwise. To remove a directory, use fs.rmdir().

More details

Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81
Shailesh Patil
  • 234
  • 2
  • 8
13

Simple and sync

if (fs.existsSync(pathToFile)) {
  fs.unlinkSync(pathToFile)
}
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
10

As the accepted answer, use fs.unlink to delete files.

But according to Node.js documentation

Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

to check files can be deleted or not, Use fs.access instead

fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
  console.log(err ? 'no access!' : 'can read/write');
});
Community
  • 1
  • 1
jasperjian
  • 383
  • 4
  • 6
  • This is a good answer, with a Node.js reference. most people will use `unlink` directly because they know they have rights to delete the file. But `fs.access` is a good alternative if they need to check before deletion. But I think if they need to check if a file exists without manipulating it afterwards, they should naturally use `fs.stat`, `fs.access` has a different purpose in my humble opinion. – vdegenne Apr 05 '18 at 13:46
  • the reason why the documentation recommends against checking for existance is because that information can change between your call to fs.stat/fs.access and the actual operation. For example the file could exist when you call fs.access and then be deleted before you call fs.unlink, or the permissions could change between the two calls. Since you have to handle the error codes of fs.unlink in that case anyways there's no point in calling fs.stat or fs.access. – Jannis Froese Mar 19 '19 at 15:21
  • This is not an answer to the question that was being asked, which is specifically about how to remove the file. (As opposed to, how to know whether you have rights to remove it.) – Steve Bennett Aug 09 '21 at 02:50
10

Here below my code which works fine.

         const fs = require('fs');
         fs.unlink(__dirname+ '/test.txt', function (err) {            
              if (err) {                                                 
                  console.error(err);                                    
              }                                                          
             console.log('File has been Deleted');                           
          });                                                            
sizzle
  • 2,222
  • 2
  • 21
  • 32
Thavaprakash Swaminathan
  • 6,226
  • 2
  • 30
  • 31
  • I like this answer the best because it's the simplest complete and correct answer for those that want to know how run something after the unlink completes and don't care about customizing the error message. – Colin Keenan Apr 15 '18 at 22:49
  • why are you using __dirname? I wonder if we could place a relative path instead of full path? – The Bumpaster Sep 16 '19 at 10:40
  • I'm using Node / Express / Multer to enable file attachments through REST POST calls. How can you expose fs.unlink in the Node / Express framework so that it can process REST DELETE calls? Posts are exposed with an app.post(...) so is something similar needed to expose the delete request? Multer may not be needed for DELETES, but what has me stuck is how to expose a workable DELETE. – Jay J Jul 16 '20 at 10:15
8

2022 Answer

Never do any sync operation in Nodejs

To asynchronously delete a file,

const { unlink } = require('fs/promises');
(async function(path) {
  try {
    await unlink(path);
    console.log(`successfully deleted ${path}`);
  } catch (error) {
    console.error('there was an error:', error.message);
}
})('/tmp/hello');

ref: https://nodejs.org/api/fs.html#promise-example

It is recommended to check file exists before deleting using access or stat

import { access, constants } from 'fs';

const file = 'package.json';

// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});

ref: https://nodejs.org/api/fs.html#fsaccesspath-mode-callback

shijin
  • 2,998
  • 1
  • 24
  • 30
  • 1
    No need to "try catch" if `unlink` is a promise. Best practice would be to use promise like ".then .catch" – Marco Jun 15 '22 at 15:29
  • 2
    @Marco Please provide documentation backing up your claim that using async/await syntax is not a best practice. – Rohn Adams Aug 19 '22 at 18:49
  • @RohnAdams Not talking async/await syntax - that looks fine. Just saying that the try/catch block is redundant and can get messy since a promise gives you the `.then` `.catch` syntax. – Marco Aug 22 '22 at 11:35
  • @Marco can you provide documentation that suggests that using the try/catch syntax with async/await is not best practice? – Rohn Adams Aug 24 '22 at 15:08
  • Thank you @RohnAdams. You got me there. I can't find anything more than Promise chain error handling is the modern way. Please then allow me to restate my comment by changing 'Best practice' to 'Modern'. – Marco Aug 26 '22 at 08:46
6
  • fs.unlinkSync() if you want to remove files synchronously and
  • fs.unlink() if you want to remove it asynchronously.

Here you can find a good article.

Benjamin Zach
  • 1,452
  • 2
  • 18
  • 38
Muhamet Smaili
  • 375
  • 2
  • 9
6

Just rm -rf it

require("fs").rmSync(file_or_directory_path_existing_or_not, {recursive: true, force: true});
// Added in Node.js 14.14.0.

with require("fs").rmSync or require("fs").rm.

3

you can use del module to remove one or more files in the current directory. what's nice about it is that protects you against deleting the current working directory and above.

const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
   console.log('Deleted files and folders:\n', paths.join('\n'));
});
Amazia Gur
  • 1,692
  • 17
  • 16
3

You may use fs.unlink(path, callback) function. Here is an example of the function wrapper with "error-back" pattern:

// Dependencies.
const fs = require('fs');

// Delete a file.
const deleteFile = (filePath, callback) => {
  // Unlink the file.
  fs.unlink(filePath, (error) => {
    if (!error) {
      callback(false);
    } else {
      callback('Error deleting the file');
    }
  })
};
Oleksii Trekhleb
  • 2,543
  • 20
  • 22
3

It's very easy with fs.

var fs = require('fs');
try{
 var sourceUrls = "/sampleFolder/sampleFile.txt";
 fs.unlinkSync(sourceUrls);
}catch(err){
 console.log(err);
}
Susampath
  • 706
  • 10
  • 13
2

Remove files from the directory that matched regexp for filename. Used only fs.unlink - to remove file, fs.readdir - to get all files from a directory

var fs = require('fs');
const path = '/path_to_files/filename.anyextension'; 

const removeFile = (fileName) => {
    fs.unlink(`${path}${fileName}`, function(error) {
        if (error) {
            throw error;
        }
        console.log('Deleted filename', fileName);
    })
}

const reg = /^[a-zA-Z]+_[0-9]+(\s[2-4])+\./

fs.readdir(path, function(err, items) {
    for (var i=0; i<items.length; i++) {
        console.log(items[i], ' ', reg.test(items[i]))
        if (reg.test(items[i])) {
           console.log(items[i])
           removeFile(items[i]) 
        }
    }
});
1

fs-extra provides a remove method:

const fs = require('fs-extra')

fs.remove('/tmp/myfile')
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})

https://github.com/jprichardson/node-fs-extra/blob/master/docs/remove.md

catch22
  • 1,564
  • 1
  • 18
  • 41
1

You can remove the file using the below codes:

Import the unlinkSync:

import { unlinkSync } from 'fs';

Can create a method like this:

export const removeFileFromLocation = async (filePath: string) => {
    const removeRes = await unlinkSync(filePath);
    return removeRes;
}

Use this method as:

const removeRes = await removeFileFromLocation(`${PATH_DOWNLOADED_FILE}/${sourceFileName}`);
console.log("removeFileFromLocation:",removeRes);

enter image description here

Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
0

Use NPM module fs-extra, which gives you everything in fs, plus everything is Promisified. As a bonus, there's a fs.remove() method available.

Jeff Breadner
  • 1,366
  • 9
  • 19
0

Those who trying to find a way to do the same in a module file, you can check out fs-extra.

import fs from 'fs-extra'

This will allow you to use any of the above-quoted methods defined by fs, there are various async actions also supported by it.

geeky01adarsh
  • 312
  • 3
  • 14
0

Promise example

Promise-based operations return a promise that is fulfilled when the asynchronous operation is complete.

import { unlink } from 'node:fs/promises';

try {
  await unlink('/tmp/hello');
  console.log('successfully deleted /tmp/hello');
} catch (error) {
  console.error('there was an error:', error.message);
}

Callback example

The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation is completed successfully, then the first argument is null or undefined.

import { unlink } from 'node:fs';

unlink('/tmp/hello', (err) => {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});
The callback-based versions of the node:fs module APIs are preferable over the use of the promise APIs when maximal performance (both in terms of execution time and memory allocation) is required.

Synchronous example

The synchronous APIs block the Node.js event loop and further JavaScript execution until the operation is complete. Exceptions are thrown immediately and can be handled using try…catch, or can be allowed to bubble up.

import { unlinkSync } from 'node:fs';

try {
  unlinkSync('/tmp/hello');
  console.log('successfully deleted /tmp/hello');
} catch (err) {
  // handle the error
}

see more

Lelik
  • 11
  • 3
-2

Here the code where you can delete file/image from folder.

var fs = require('fs'); 
Gallery.findById({ _id: req.params.id},function(err,data){ 
    if (err) throw err;
    fs.unlink('public/gallery/'+data.image_name);
 });
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
  • Since node 7 the callback argument is no longer optional and will result in a warning. Pass an empty function if you really don't care about it. – jlh Jul 24 '17 at 12:14