Another common task when working with the file system is listing files and folders in a directory—for example, listing the files in a directory to determine whether they need to be cleaned up, to dynamically operate on the directory structure, etc.
You can access the files in the file system by using one of the following commands to read a list of entries:
fs.readdir(path, callback)
fs.readdirSync(path)
If readdirSync()
is called, an array of strings representing the entry names in the specified path
is returned. In the case of readdir()
, the list is passed as the second parameter to the callback function, and an error, if there is one, is passed as the first parameter.
To illustrate the use of readdir()
, the code in Listing 6.10 implements a nested callback chain to walk the directory structure and output the entries. Notice that the callback function implements a wrapper to provide closure for the fullPath
variable and that the WalkDirs()
function loops by being called by the asynchronous callback function. Figure 6.10 shows the results.
01 var fs = require('fs'),
02 var Path = require('path'),
03 function WalkDirs(dirPath){
04 console.log(dirPath);
05 fs.readdir(dirPath, function(err, entries){
06 for (var idx in entries){
07 var fullPath = Path.join(dirPath, entries[idx]);
08 (function(fullPath){
09 fs.stat(fullPath, function (err, stats){
10 if (stats && stats.isFile()){
11 console.log(fullPath);
12 } else if (stats && stats.isDirectory()){
13 WalkDirs(fullPath);
14 }
15 });
16 })(fullPath);
17 }
18 });
19 }
20 WalkDirs("../ch06");