2013-09-24 12:46:30 +02:00
|
|
|
var when = require('when'),
|
|
|
|
keys = require('when/keys'),
|
|
|
|
fs = require('fs'),
|
|
|
|
path = require('path'),
|
2013-06-25 13:43:15 +02:00
|
|
|
extend = function (obj, source) {
|
|
|
|
var key;
|
|
|
|
for (key in source) {
|
|
|
|
if (source.hasOwnProperty(key)) {
|
|
|
|
obj[key] = source[key];
|
2013-06-09 18:45:17 +02:00
|
|
|
}
|
2013-06-25 13:43:15 +02:00
|
|
|
}
|
|
|
|
return obj;
|
|
|
|
},
|
|
|
|
readDir = function (dir, options, depth) {
|
|
|
|
depth = depth || 0;
|
2013-06-09 18:45:17 +02:00
|
|
|
|
2013-06-25 13:43:15 +02:00
|
|
|
options = extend({
|
|
|
|
index: true
|
|
|
|
}, options);
|
2013-06-09 18:45:17 +02:00
|
|
|
|
2013-06-25 13:43:15 +02:00
|
|
|
if (depth > 1) {
|
|
|
|
return null;
|
|
|
|
}
|
2013-06-09 18:45:17 +02:00
|
|
|
|
2013-06-25 13:43:15 +02:00
|
|
|
var subtree = {},
|
|
|
|
treeDeferred = when.defer(),
|
|
|
|
treePromise = treeDeferred.promise;
|
2013-06-15 16:20:30 +02:00
|
|
|
|
2013-06-25 13:43:15 +02:00
|
|
|
fs.readdir(dir, function (error, files) {
|
|
|
|
if (error) {
|
|
|
|
return treeDeferred.reject(error);
|
|
|
|
}
|
2013-06-15 16:20:30 +02:00
|
|
|
|
2013-06-25 13:43:15 +02:00
|
|
|
files = files || [];
|
2013-06-09 18:45:17 +02:00
|
|
|
|
2013-06-25 13:43:15 +02:00
|
|
|
files.forEach(function (file) {
|
|
|
|
var fileDeferred = when.defer(),
|
|
|
|
filePromise = fileDeferred.promise,
|
|
|
|
ext = path.extname(file),
|
|
|
|
name = path.basename(file, ext),
|
|
|
|
fpath = path.join(dir, file);
|
|
|
|
subtree[name] = filePromise;
|
|
|
|
fs.lstat(fpath, function (error, result) {
|
2013-10-31 19:02:34 +01:00
|
|
|
/*jslint unparam:true*/
|
2013-06-25 13:43:15 +02:00
|
|
|
if (result.isDirectory()) {
|
|
|
|
fileDeferred.resolve(readDir(fpath, options, depth + 1));
|
|
|
|
} else {
|
|
|
|
fileDeferred.resolve(fpath);
|
|
|
|
}
|
2013-06-09 18:45:17 +02:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2013-07-31 10:21:22 +02:00
|
|
|
return keys.all(subtree).then(function (theFiles) {
|
2013-06-25 13:43:15 +02:00
|
|
|
return treeDeferred.resolve(theFiles);
|
2013-06-09 18:45:17 +02:00
|
|
|
});
|
2013-06-25 13:43:15 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
return when(treePromise).then(function (prom) {
|
|
|
|
return prom;
|
|
|
|
});
|
|
|
|
},
|
|
|
|
readAll = function (dir, options, depth) {
|
|
|
|
return when(readDir(dir, options, depth)).then(function (paths) {
|
|
|
|
return paths;
|
|
|
|
});
|
|
|
|
};
|
2013-06-09 18:45:17 +02:00
|
|
|
|
2013-10-31 19:02:34 +01:00
|
|
|
module.exports = readAll;
|