anon
anon

Reputation:

Why does remove directory give an error in this case?

So, I have been studying the filesystem module and also I am quite new to async and await I don't understand why am I getting error here?

const fs = require("fs");
async function removeDir() {
    await fs.readdir("./trash", (err, files) => {
        if (err) throw err;

        for(filename of files){
            fs.unlinkSync(`./trash/${filename}`);
        }
        
        console.log("Cleared all files within directory");
    });

    await fs.rmdir("./trash", err => {
        if (err) throw err;

        console.log("Removed Dir");
    });
}
removeDir();

Why is fs.rmdir getting executed before removing the files in the directory and I am getting an error that the directory isn't empty. Why isn't await working as I am expecting it to work.

Upvotes: 1

Views: 75

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

readdir in the main fs module doesn't return a promise, so using await on it has (almost) no effect, and certainly doesn't make the code wait until it's done its job. (That's why it has a callback, because that's how you know it's done.) Same for rmdir.

You can use the versions from the newer fs/promises API instead.


Side note: Your code is falling prey to what I call The Horror of Implicit Globals because you never declare filename. Always be sure to declare your variables. (In this case, just put const in front of filename: for (const filename of files) {.) I also recommend using strict mode so that trying to assign to an undeclared identifier is the error it always should have been. These days, the best way to do that is to use JavaScript modules, which are always in strict mode. But you can use "use strict"; at the top of a script or old-style Node.js module instead.

Upvotes: 1

Related Questions