Having trouble understanding how fs.stat() works

Asher Saban picture Asher Saban · Dec 20, 2011 · Viewed 35.1k times · Source

I'm trying to write a function that tells me is a certain path is a directory.

var fs = require('fs');
console.log("+++++++++++++++++++++++++++++++++++++++");
fs.statSync(pathname, function(err, stats) {
    console.log(stats.isDirectory());
});
console.log("+++++++++++++++++++++++++++++++++++++++");

However, it never prints the answer.

If pathname exists - it doesn't call the function. If it doesn't exists, it generates an exception: ENOENT not a file or directory. I don't want to know it pathname exists, but I want to know if it's a directory.

Can anyone help me fix it?

Answer

Alex Wayne picture Alex Wayne · Dec 20, 2011

You are using the synchronous version, which doesn't use a callback. It simply returns the result instead. So either use the async form fs.stat(path, callback) or use the sync form like this:

var fs = require('fs');
console.log("+++++++++++++++++++++++++++++++++++++++");
var stats = fs.statSync(pathname);
console.log(stats.isDirectory());
console.log("+++++++++++++++++++++++++++++++++++++++");