Skip to content

Instantly share code, notes, and snippets.

@simov
Last active August 29, 2015 14:14
Show Gist options
  • Save simov/2f09e93a380dd9e29c40 to your computer and use it in GitHub Desktop.
Save simov/2f09e93a380dd9e29c40 to your computer and use it in GitHub Desktop.
Recursively read directory using generators, co and thunkify
var fs = require('fs')
, path = require('path')
, co = require('co')
, thunkify = require('thunkify')
, readdir = thunkify(fs.readdir)
, stat = thunkify(fs.stat)
var recursive = co.wrap(function* (root) {
var dirs = [], files = []
dirs.push(root)
var readdirr = co.wrap(function* (root) {
var items = yield readdir(root)
for (var i=0; i < items.length; i++) {
var fpath = path.join(root, items[i])
var stats = yield stat(fpath)
if (stats.isDirectory()) {
dirs.push(fpath)
yield readdirr(fpath)
} else {
files.push(fpath)
}
}
return {dirs:dirs, files:files}
})
return readdirr(root)
.then(function (result) {return result})
.catch(function (err) {throw err})
})
// run
var root = '/absolute/path/to/some/dir/you/want/to/read'
recursive(root)
.then(function (result) {console.log(result)})
.catch(function (err) {console.log(err)})
@Globik
Copy link

Globik commented Aug 22, 2015

Depth only for one step :) it's not quite recursive)

@Globik
Copy link

Globik commented Aug 25, 2015

Oh, I'm sorry, all is right here, I tested this code one more. Only anyone should use recursive method with yield: var result; yield recursive(root).then(f(result){result=result})....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment