Skip to content

Instantly share code, notes, and snippets.

@edygar
Last active August 29, 2015 14:04
Show Gist options
  • Save edygar/ee0945a73c79182367df to your computer and use it in GitHub Desktop.
Save edygar/ee0945a73c79182367df to your computer and use it in GitHub Desktop.
Get subdirectories asynchronously
var fs = require('fs');
module.exports = function getSubDirectories( dir )
{
var deferred = new Promise();
var dirs = [], count = 0;
fs.readdir(dir, function(err, files)
{
if (err) deferred.error(err);
if (!files.length) return deferred.resolve([]);
files.forEach(function( file )
{
stat(dir, function(err, fileInfo)
{
if (err) deferred.error(err);
if (fileInfo.isDirectory())
dirs.push(file);
count++;
if (count === files.length)
deferred.resolve(dirs);
})
});
});
return dirs;
}
var Rx = require('rx'),
fs = require('fs'),
readdir = Rx.Observable.fromNodeCallback(fs.readdir),
stat = Rx.Observable.fromNodeCallback(fs.statS);
Array.prototype.toObservable = function()
{
return Rx.Observable.fromAarray(this);
}
module.exports = function getSubDirectoriesRx(param)
{
return readdir(param)
.mapFlat(function(files)
{
return files
.map(function(file)
{
return stat(file)
.filter(function(fileInfo) {
return fileInfo.isDirectory()
})
.map(function() { return file })
})
.toObservable()
.mergeAll();
});
}
Copy link

ghost commented Jan 8, 2015

Here's a version that uses only rx for mapping: (coffeescript)

Rx = require "rx"
fs = require "fs"

readdir = Rx.Observable.fromNodeCallback fs.readdir
stat = Rx.Observable.fromNodeCallback (pathName, cb) ->
    fs.stat pathName, (err, stats) ->
        stats.pathName = pathName
        cb err, stats

dirObservable = (dirPath) ->
    readdir dirPath
        .flatMap (items) -> Rx.Observable.from items
        .flatMap (item) -> stat item
        .filter (stats) -> stats.isDirectory()
        .map (stats) -> stats.pathName

module.exports = dirObservable


if not module.parent
    path = require "path"
    dirobs = dirObservable path.resolve __dirname, ".."
    dirobs.subscribe (data) -> console.log data

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