Node.js fs.unlink 函数导致 EPERM 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8496212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:52:57  来源:igfitidea点击:

Node.js fs.unlink function causes EPERM error

node.js

提问by Mark Gia Bao Nguyen

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

我正在使用fs.unlink()删除文件,但收到以下错误:

uncaught undefined: 

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

Anyone know a why this is happening?

有谁知道为什么会这样?

回答by Raghavendra

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

您不能删除非空目录。fs.unlinkSync() 用于删除文件而不是文件夹。

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

要删除空文件夹,请使用 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?

来自 stackoverflow 的片段:node.js rmdir 是递归的吗?它可以在非空目录上工作吗?

回答by David Lin

If you want to achieve something like rm -rf does, there is a package from npm called rimrafwhich makes it very easy.

如果你想实现像 rm -rf 那样的东西,npm 有一个名为rimraf的包,它非常容易。

回答by JR Grande

Maybe the Pathof the file is located is erroneus.

也许文件所在的路径是错误的。

if not, try with fs.unlinkSync()

如果没有,请尝试使用fs.unlinkSync()

回答by thejh

Yes, you don't have permission to delete/unlink that file. Try again with more rights or verify that you're giving it the right path.

是的,您无权删除/取消链接该文件。使用更多权限重试或验证您提供的路径是否正确。