How to get files from a directory?


#1

Using docs from here I’ve manage to get the path from a directory, but now I want to loop through its files (including sub-directories).

Any idea how I might achieve that? Thank you :smile:


#2

You could use node’s fs module’s readdir method. It would look something like

fs.readdir myDir, (dir) ->
  for filePath in dir
    console.log filePath

#3

Thank you. Could you please write that code in JS? It looks like coffee script and I don’t really know it :blush:


#4

Oh, right :stuck_out_tongue:

fs.readDir(myDir, function(dir) {
  // es5
  for(var i = 0, l = dir.length; i < l; i++) {
    var filePath = dir[i];
    console.log(filePath)
  }
  // es6
  for(let filePath of dir) {
    console.log(filePath);
  }
});

#5

Latest version of node use diffrent version of call-back fucntion.

const fs = require(“fs”);

fs.readdir(’.’, (err, dir) => {
//console.log(dir);
for(let filePath of dir)
console.log(filePath);
});


#6

Just use:

fs.readdir('.', (err, dir) => {
        for (var i = 0, path; path = dir[i]; i++) {
                // do stuff with path
        }
});

if you want to loop through a list is what I do.