Skip to content

Instantly share code, notes, and snippets.

@ukstv
Created December 10, 2010 11:19
Show Gist options
  • Save ukstv/736097 to your computer and use it in GitHub Desktop.
Save ukstv/736097 to your computer and use it in GitHub Desktop.
Directory tree traversal
fs = require('fs')
util = require('util')
path = require('path')
flatten = (a, b) ->
if typeof b is 'undefined'
b = a
a = []
b = b.reduce(flatten, []) if typeof b is 'object'
a = [a] if typeof a isnt 'object'
a.concat(b)
traverse = (index, list, callback) ->
[index, list, callback] = [0, index, list] if arguments.length == 2
fs.readdir list[index], (err, files) ->
if files? # Directory
files = files.map (f) -> path.join(list[index], f)
list.splice index, 1, files
list = flatten(list)
traverse(0, list, callback)
else # File
nxt = index + 1 # Move forward?
if nxt < list.length then traverse(nxt, list, callback) else callback(list)
traverse [__dirname], (files) ->
console.log(files)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment