noddy asked this 4 years ago

Node.js check if a path is a file or directory

How to check if a path is file or directory?

Best Answer by mkbaines 4 years ago

Information about a file or directory can be retrieved asynchronously using fs.stat() or fs.lsstat()

fs.stat(path,callback) . The callback takes 2 arguments (err,stats) . The stats is fs.Stats object. It has methods for checking file or directory.

fs.stat(filePath, function (err, stats) {
     if (err) {
     else {
	   	console.log(filePath + " is a directory");
	     else if(stats.isFile())
	   	console.log(filePath + " is a file");
	     else {
	   	// optionally check for BlockDevice, CharacterDevice etc
	   	console.log(filePath + " is not a file or directory");

The synchronous versions for stat/lsstat are fs.statSync() and fs.lsstatSync()