Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js fs.unlink function causes EPERM error

Tags:

node.js

I'm using fs.unlink() to delete a file and I receive the following error:

uncaught undefined: 

Error: EPERM, Operation not permitted '/Path/To/File'

Anyone know a why this is happening?

like image 532
Mark Nguyen Avatar asked Dec 13 '11 21:12

Mark Nguyen


People also ask

What does FS unlink do?

The fs. unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.

Is FS unlink async?

Node offers a synchronous method, and an asynchronous method through the fs built-in module. The asynchronous one is fs. unlink() .

How do I unlink files in node?

In Node. js, you can use the fs. unlink() method provided by the built-in fs module to delete a file from the local file system.


1 Answers

You cannot delete a directory that is not empty. And fs.unlinkSync() is used to delete a file not a folder.

To remove an empty folder, use fs.rmdir()

to delete a non empty folder, use this snippet:

var deleteFolderRecursive = function(path) {
  if( fs.existsSync(path) ) {
      fs.readdirSync(path).forEach(function(file) {
        var curPath = path + "/" + file;
          if(fs.lstatSync(curPath).isDirectory()) { // recurse
              deleteFolderRecursive(curPath);
          } else { // delete file
              fs.unlinkSync(curPath);
          }
      });
      fs.rmdirSync(path);
    }
};

Snippet from stackoverflow: Is node.js rmdir recursive ? Will it work on non empty directories?

like image 84
Raghavendra Avatar answered Sep 21 '22 03:09

Raghavendra