Last active
August 29, 2015 14:14
-
-
Save simov/2f09e93a380dd9e29c40 to your computer and use it in GitHub Desktop.
Recursively read directory using generators, co and thunkify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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})....