Skip to content

Instantly share code, notes, and snippets.

@thomasnorris
Last active August 13, 2018 16:59
Show Gist options
  • Save thomasnorris/1b58af057f6c0f1f03343031c7239555 to your computer and use it in GitHub Desktop.
Save thomasnorris/1b58af057f6c0f1f03343031c7239555 to your computer and use it in GitHub Desktop.
Automatically import local .js files into other files, similar to importing npm packages
// --Place in project's node_modules folder
// --Set this at the top of the main program.js
// global.requireLocal = require('local-modules.js').GetModule;
// --Call with requireLocal('file-to-get') to automatically get the right file
var _paths;
// --Add a root dir to scan through, or leave as '' to scan all folders (including node_modules)
var _rootDirName = '';
module.exports = {
GetModule: function(name) {
if (!_paths || _paths.length == 0)
GetAllFilePaths();
try {
var path = _paths.filter((el) => {
return el.toLowerCase().includes(name.toLowerCase());
}).toString();
if (path == '')
throw 'File \"' + name + '\" not found';
} catch (err) {
console.log('There was an error: ' + err);
process.exit(0);
}
return require(path);
function GetAllFilePaths() {
var _fs = require('fs');
_paths = ScanDirectory(__dirname + '/..' + _rootDirName);
function ScanDirectory(dir) {
var results = [];
var list = _fs.readdirSync(dir);
list.forEach((file) => {
file = dir + '/' + file;
var stat = _fs.statSync(file);
if (stat && stat.isDirectory())
results = results.concat(ScanDirectory(file));
else
results.push(file);
});
return results;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment