Skip to content

Instantly share code, notes, and snippets.

@Cosrnos
Last active August 29, 2015 14:07
Show Gist options
  • Save Cosrnos/e99d07e98891d28d73e9 to your computer and use it in GitHub Desktop.
Save Cosrnos/e99d07e98891d28d73e9 to your computer and use it in GitHub Desktop.
Recursively Reads a config folder then returns it as an object
/*
* Asynchronously and Recursively reads a configuration folder and builds a configuration object.
*/
// Libs
var RSVP = require('rsvp');
var fs = require('fs');
var _ = require('underscore');
var loq = require('lo-q');
module.exports = {};
function read_directory(path) {
return new RSVP.Promise(function(resolve, reject) {
fs.readdir(path, function(err, res) {
if (err || !res) {
return reject(err || "Could not retrieve a list of files in directory " + path);
}
return resolve(res);
});
});
}
function stat_file(path) {
return new RSVP.Promise(function(resolve, reject) {
fs.stat(path, function(err, result) {
if (err || !result) {
return reject(err || "Could not retrieve file stats for file " + path);
}
return resolve(result);
});
});
}
function is_dir(path) {
return new RSVP.Promise(function(resolve, reject) {
stat_file(path).then(function(stats) {
resolve(stats.isDirectory())
}).catch(function(err) {
reject(err);
});
});
}
function get_config(path) {
return require('./' + path);
};
function hash_files(path, files, obj) {
return new RSVP.Promise(function(resolve, reject) {
var hash = {};
_.each(files, function(file) {
hash[file] = new RSVP.Promise(function(file_res, file_rej) {
is_dir(path + "/" + file).then(function(is_dir) {
if (is_dir) {
obj[file] = {};
file_res(recursive_read(path + "/" + file, obj[file]));
} else {
//definitely a file...
var name = file.replace(/\.js/g, '');
if (path.substr(path.length - name.length, name.length) === name) {
/* If the name of our file shares the name of our directory, we
* want to put the contents of the file at the root of the object
* since they should be namespaced similarily.
*/
_.extend(obj, get_config(path + "/" + file));
} else {
obj[name] = get_config(path + "/" + file);
}
file_res();
}
}).catch(function(err) {
reject(err);
});
});
});
RSVP.hash(hash).then(function() {
resolve('thing');
}).catch(function(err) {
reject(err);
});
});
}
function recursive_read(path, obj) {
return new RSVP.Promise(function(resolve, reject) {
read_directory(path).then(function(files) {
resolve(hash_files(path, files, obj));
}).catch(function(error) {
reject(error);
});
});
}
var x = {};
recursive_read('config', x).then(function() {
loq.object(x);
}).catch(function(err) {
console.log(err);
});
@mseeks
Copy link

mseeks commented Oct 7, 2014

I'll be honest. Javascript is not my strongest language. ^_^

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