List files using Node.js

Neat code snippet  to recursively list files of a directory using Node.js

/* Bad error handling though ...*/
var fs = require('fs');
var path = require('path');
var dirToList = 'path/to/dir';
var listFiles = function(dir) {
  fs.readdir(dir, function(error, items) {
    for (var index in items) {
      var filePath = path.join(dir, items[index]);
      (function(fullFilePath) {
        fs.stat(fullFilePath, function(error, stats) {
          if (stats && stats.isFile()) {
            console.log(fullFilePath);
          } else if (stats && stats.isDirectory()) {
            listFiles(fullFilePath);
          }
        })
      })(filePath);
    }
  })
}
listFiles(dirToList);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s