3

I am very new to server side programming and NodeJS

I need to read a directory recursively to get the file name of each file in this directory ( an array of file names ( relative paths) should be returned)

I think it is some thing very common so I am hoping if someone can share the code. Or just tell me the right methods to call. Thanks

Codier
  • 2,126
  • 3
  • 22
  • 33
  • 1
    possible duplicate of [getting all filenames in a directory with node.js](http://stackoverflow.com/questions/2727167/getting-all-filenames-in-a-directory-with-node-js) – razlebe Oct 27 '11 at 14:49

4 Answers4

5

Here is my first shot at it.

fs = require('fs');

function getDirectoryFiles(directory, callback) {
  fs.readdir(directory, function(err, files) {
    files.forEach(function(file){
      fs.stat(directory + '/' + file, function(err, stats) {
        if(stats.isFile()) {
          callback(directory + '/' + file);
        }
        if(stats.isDirectory()) {
          getDirectoryFiles(directory + '/' + file, callback);
        }
      });
    });
  });
}

getDirectoryFiles('.', function(file_with_path) {
  console.log(file_with_path);
});

Of course instead of the console.log in the callback handling function you could push the values in a global array.

mhitza
  • 5,709
  • 2
  • 29
  • 52
3

You can do this easily with the files method of the node-dir module:

Install the module

npm install node-dir

Then the code is as simple as

var dir = require('node-dir');

dir.files(__dirname, function(err, files) {
  if (err) throw err;
  console.log(files);
});

This will recurse through all subdirectories and result will be an array of file paths.

fshost
  • 919
  • 5
  • 3
1

Also this may help: do async task on each file recursively and execute callback when done

Community
  • 1
  • 1
Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75
0

check out loaddir https://npmjs.org/package/loaddir

npm install loaddir

  loaddir = require('loaddir')

  allJavascripts = []
  loaddir({
    path: __dirname + '/public/javascripts',
    callback: function(){  allJavascripts.push(this.relativePath + this.baseName); }
  })

You can use fileName instead of baseName if you need the extension as well.

dansch
  • 6,059
  • 4
  • 43
  • 59