UNPKG

1.09 kBJavaScriptView Raw
1var PathHelpers = module.exports = {
2 loadModules: loadModules,
3 isDirSync: isDirSync
4};
5
6// Loads mixin modules in a path.
7// Finds all module files in `filepath` and gives them to `callback`.
8// to each of those functions.
9//
10// loadModules('app/migrations/', 'function', function(m) { ... });
11//
12function loadModules(filepath, type, callback) {
13 var fs = require('fs');
14 var path = require('path');
15
16 var self = this;
17
18 if (!isDirSync(filepath)) return;
19
20 var files = fs.readdirSync(filepath);
21 files = files.sort();
22
23 files.forEach(function(file) {
24 // Igonre files without extensions.
25 if (file.indexOf('.') === -1) return;
26
27 var fn = path.resolve(filepath, file);
28
29 // Ignore directories.
30 if (isDirSync(fn)) return;
31
32 // Ensure it's the right type.
33 var module = require(fn);
34 if (typeof module !== type) return;
35
36 callback(module);
37 });
38}
39
40// Checks if a given path is a directory.
41function isDirSync(fn) {
42 var fs = require('fs');
43
44 if (!fs.existsSync(fn)) return false;
45
46 var stat = fs.statSync(fn);
47 return stat.isDirectory();
48}