fs-file-tree
Version:
Get a directory file tree as an object.
118 lines (101 loc) • 3.34 kB
JavaScript
;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var readDir = require("read-dir-and-stat"),
path = require("path"),
sameTime = require("same-time"),
bindy = require("bindy"),
camelo = require("camelo"),
assured = require("assured");
/**
* fsFileTree
* Get a directory file tree as an object.
*
* @name fsFileTree
* @function
* @param {String} inputPath The input path.
* @param {Object} opts An object containing the following fields:
*
* - `camelCase` (Boolean): Convert the file names in camelcase format (to be easily accessible using dot notation).
* - `all` (Boolean): If `true`, it will include the hidden files/directories.
*
* @param {Function} cb The callback function.
*/
function fsFileTree(inputPath, opts, cb) {
var result = {};
if (typeof inputPath === "function") {
cb = inputPath;
inputPath = process.cwd();
opts = {};
} else if (typeof opts === "function") {
cb = opts;
if ((typeof inputPath === "undefined" ? "undefined" : _typeof(inputPath)) === "object") {
opts = inputPath;
inputPath = process.cwd();
} else {
opts = {};
}
}
opts = opts || {};
cb = assured(cb);
readDir(inputPath, function (err, items) {
if (err) {
return cb(err);
}
sameTime(bindy(items, function (c, done) {
var basename = path.basename(c.path);
if (basename.charAt(0) === "." && !opts.all) {
return done();
}
if (opts.camelCase) {
basename = camelo(basename);
}
if (c.stat.isDirectory()) {
return fsFileTree(c.path, opts, function (err, res) {
if (err) {
return done(err);
}
result[basename] = res;
done();
});
}
result[basename] = c;
done();
}), function (err) {
return cb(err, result);
});
});
return cb._;
}
/**
* sync
* The sync version.
*
* @name sync
* @function
* @param {String} inputPath The input path.
* @param {Object} opts An object containing the following fields:
*
* - `camelCase` (Boolean): Convert the file names in camelcase format (to be easily accessible using dot notation).
* - `all` (Boolean): If `true`, it will include the hidden files/directories.
*
* @returns {Object} The directory tree.
*/
fsFileTree.sync = function (inputPath, opts) {
var result = {};
opts = opts || {};
readDir.sync(inputPath).forEach(function (c) {
var basename = path.basename(c.path);
if (basename.charAt(0) === "." && !opts.all) {
return;
}
if (opts.camelCase) {
basename = camelo(basename);
}
if (c.stat.isDirectory()) {
return result[basename] = fsFileTree.sync(c.path, opts);
}
result[basename] = c;
});
return result;
};
module.exports = fsFileTree;