Error: ENOENT: no such file or directory, unlink

17,645

Solution 1

Can you try this instead:

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

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

Solution 2

You should first install the path module via CLI:

npm install path --save

and use it:

fs.unlink(path.join("public/" + path, photo.id + ".jpg"), function(response) {
  // handle the callback
});
Share:
17,645
Rasit aydin
Author by

Rasit aydin

Updated on June 14, 2022

Comments

  • Rasit aydin
    Rasit aydin about 2 years

    As you can see, there is a file at the path. But fs says no such file or directory. I can't understand why?

    In another file, I can remove with the same code.

    My boat.js file:

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

    And it is my error:

    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

  • Rasit aydin
    Rasit aydin about 6 years
    thank you for your comment, but string in path variable begining with /. Actually, path in error is right path and exist.
  • Rasit aydin
    Rasit aydin about 6 years
    Hi @shubhambharti201, this worked !! But why ? Can you explain ? Why I shouldn't use "../" ?
  • Rasit aydin
    Rasit aydin about 6 years
    Hi, thank you for your answer, but @shubhambharti201's answer is worked for me. thank for helping :)
  • shubhambharti201
    shubhambharti201 about 6 years
    In loopback (nodejs framework), the main directory where the node_modules/ lies, is taken as the reference directory. And "../" means you are going out of that main project directory.
  • abu abu
    abu abu about 5 years
    your solution is helpful. Thanks.