Error: ENOENT: no such file or directory, unlink

Error: ENOENT: no such file or directory, unlink

如您所见,路径中有一个文件。但是 fs 说没有这样的文件或目录。我不明白为什么?

在另一个文件中,我可以使用相同的代码删除。

我的 boat.js 文件:

boat.findById(req.params.id,function(err, foundBoat) {
    if(err){
        console.log(err);
    }else{
        foundBoat.boatsFoto.forEach(function(path){
            console.log(typeof(path));
            fs.unlink("../public"+path,function(err){
                if(err) throw err;

                console.log('File deleted!');
            });
        });
    } 
});

这是我的错误:

Error: ENOENT: no such file or directory, unlink '../public/uploads/akingokay/BoatsFoto/1524411110335kiralik-tekne.jpg'
at Error (native)

And you can see my file system

检查您添加到“/public”的路径变量是否以“/”开头。如果没有/分开它会将路径视为一个路径。

你能试试这个吗:

fs.unlink("public"+path,function(err){
    if(err) throw err;

    console.log('File deleted!');
});

安装并导入 path 模块。这对你有帮助 https://nodejs.org/api/path.html

而不是 "../public"+path 使用 path.join("../", "public", path);

您应该首先通过 CLI 安装 path 模块:

npm install path --save

并使用它:

fs.unlink(path.join("public/" + path, photo.id + ".jpg"), function(response) {
  // handle the callback
});

这取决于您托管服务器的位置。如果它在本地机器上,那么您可能需要指定要删除或操作的文件的完整路径。如果它位于活动的网络服务器上,那么您将需要指定它的完整路径。

在“本地机器”上它可能看起来像这样:

fs.unlink('/home/user/project/someothername/'+filename, err => {
// handler
});

考虑一下你在app.js文件中,并给出删除文件的相对路径到fs.unlink('path/to/file')。它会起作用的!