Created
March 27, 2014 21:23
-
-
Save CrabDude/9819245 to your computer and use it in GitHub Desktop.
ListDir: Async Generator all the things!
This file contains hidden or 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
// List all files recursively within a directory with maximum parallelism | |
"use strict"; | |
let path = require('path') | |
let fs = require('fs') | |
let co = require('co') | |
let _ = require('lodash') | |
Function.prototype.partial = function() { | |
var args = Array.prototype.slice.call(arguments) | |
args.unshift(null) | |
return this.bind.apply(this, args) | |
} | |
function* statFile(filePath) { | |
var stat = yield fs.stat.partial(filePath) | |
if (stat.isDirectory()) { | |
return yield listDir(filePath) | |
} else { | |
return filePath.replace(__dirname, '.') | |
} | |
} | |
function* listDir(dir) { | |
var files = yield fs.readdir.partial(dir) | |
return yield files.map(function(fileName) { | |
var filePath = path.join(dir, fileName) | |
return statFile(filePath) | |
}) | |
} | |
co(function* () { | |
_(yield listDir(__dirname)) | |
.flatten() | |
.each(function(filePath) { | |
console.log(filePath) | |
}) | |
// Or, call a generator, but don't wait | |
co(listDir)(__dirname) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment