I managed to get it working. Here are my answers to my own questions:
It is better to perform the tasks asynchronously because to do it otherwise would mean that the application would block other users from receiving their responses until subsequent requests have been responded to.
The way to convert the synchronous code to asynchronous code is to use a parallel loop. The code for my particular case is this:
var path = require('path'); var fs = require('fs'); exports.browse2 = function(request, response) { getFolderContents( 'C:\\Users\\AccountName\\folder1\\folder2\\folder3\\test\\', function(err, tree) { if (err) throw err; response.send(tree); }); }; function getFolderContents(route, callback) { var branch = {}; branch.title = path.basename(route); branch.folder = true; branch.children = []; fs.readdir(route, function(err, files) { if (err) return callback(err); var pending = files.length; if (!pending) return callback(null, branch); files.forEach(function(file) { var concatPath = path.join(route, file); fs.lstat(concatPath, function(err, stats) { if (stats && stats.isDirectory()) { getFolderContents(concatPath, function(err, res) { branch.children.push(res); if (!--pending) callback(null, branch); }); } else { branch.children.push({ "title" : path.basename(file), "path" : file }); if (!--pending) callback(null, branch); } }); }); }); }
Thanks to user "chjj" with his response to a similar question on this thread: node.js fs.readdir recursive directory search
And thanks to user "Dan Smolinske" for directing me to the thread.