fs.realpath(path, [cache], callback)

fs.readdir(path, callback)

fs.stat(path, callback)

var fs = require('fs');

function traverseDirectory(dirname, callback) {

var directory = [];

fs.readdir(dirname, function(err, list) {

dirname = fs.realpathSync(dirname);

if (err) {

return callback(err);

}

var listlength = list.length;

list.forEach(function(file) {

file = dirname + '\\' + file;

fs.stat(file, function(err, stat) {

directory.push(file);

if (stat && stat.isDirectory()) {

traverseDirectory(file, function(err, parsed) {

directory = directory.concat(parsed);

if (!--listlength) {

callback(null, directory);

}

});

} else {

if (!--listlength) {

callback(null, directory);

}

}

});

});

});

}

traverseDirectory(__dirname, function(err, result) {

if (err) {

console.log(err);

}

console.log(result);

});





In this post we will show you how to navigate through directories in Nodejs. In our previous post How to get list of files in a directory in Nodejs , we have shown how to get list of files in a directory in Nodejs. But what if we have a folder inside that directory, that code will not traverse through the folders.Before going into the code we will take you through some of the methods which we are using in this code.Using this method we will pass the path as our current directory, the callback gets two arguments for us (err, path). This method is used to get the path we are currently in.Using this method we will be reading contents of a directory. The callback gets two arguments (err, files) where files ia an array of the names of the files in the directory.The callback gets two arguments (err, stats) where stat is a fs.stats object. For more information about fs.stats check here So, If you have a directory named 'example' and have below contents in itAfter running the above code you will get the output asPlease Like and Share the Blog, if you find it interesting and helpful.