node.js remove file

The Question :

616 people think this question is useful

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?

The Question Comments :

The Answer 1

856 people think this answer is useful

I think you want to use fs.unlink.

More info on fs can be found here.

The Answer 2

251 people think this answer is useful

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

The Answer 3

66 people think this answer is useful

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

The Answer 4

37 people think this answer is useful

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

The Answer 5

28 people think this answer is useful

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

The Answer 6

11 people think this answer is useful

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.

The Answer 7

10 people think this answer is useful

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

The Answer 8

7 people think this answer is useful

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

The Answer 9

3 people think this answer is useful

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

The Answer 10

3 people think this answer is useful
  • 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.

The Answer 11

2 people think this answer is useful

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

The Answer 12

2 people think this answer is useful

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

The Answer 13

2 people think this answer is useful

It’s very easy with fs.

var fs = require('fs');
try{
 var sourceUrls = "/sampleFolder/sampleFile.txt";
 fs.unlinkSync(sourceUrls);
}catch(err){
 console.log(err);
}

The Answer 14

1 people think this answer is useful

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

The Answer 15

0 people think this answer is useful

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.

The Answer 16

0 people think this answer is useful

Simple and sync

if (fs.existsSync(pathToFile)) {
  fs.unlinkSync(pathToFile)
}

The Answer 17

0 people think this answer is useful

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#fs_fs_rmsync_path_options

The Answer 18

-1 people think this answer is useful

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

Tags:

Add a Comment