How to get files from a directory?


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:


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


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


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];
  // es6
  for(let filePath of dir) {


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

const fs = require(“fs”);

fs.readdir(’.’, (err, dir) => {
for(let filePath of dir)


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.