Explanation needed on Node.js and the stack

I have some code taken from a tutorial, and it works, but from my understanding of the stack and callback functions it shouldn’t. The code creates a directory called stuff, then creates a new file and writes a short array to that file.

Doesn’t the mkdir function get added to the stack first, and then the writeFile function? Meaning that the writeFile function is the first to fire, and it should fail as ./stuff doesn’t exist yet?

Can some please explain?

let arr2 = [1,2,3,4];
fs.mkdir("stuff", function (err){
    if (err) throw err;
    fs.writeFile("./stuff/newfile.txt", arr2, function (err){
        if (err) throw err;
    })
})

Callback in .mkdir will be invoked only when it’s finished with creating the directory. In other words .writeFile will be added on top of .mkdir when the directory will exist, not immediately.

Thanks! Makes sense, appreciate it :slight_smile: