NodeJS Asynchronous Module Loader (file injection)

JS
S
JavaScript

Simple snippet to load modules asynchronously on NodeJS. Requirements: Node 6.4.0+ File Structure: /index.js //entrypoint /files/file1.js /files/file2.js To run: node index.js / nodemon index.js / pm2 index.js

1// =====================================================================
2// index.js
3'use strict';
4const fs = require('fs');
5const path = require('path');
6
7const loader = (function() {
8  let startFolder = null,
9
10  //Called once for loading all files
11  load = folderName => {
12    if (!startFolder) startFolder = path.basename(folderName);
13
14    fs.readdirSync(folderName).forEach(file => {
15      const fullName = path.join(folderName, file);
16      const stat = fs.lstatSync(fullName);
17
18      if (stat.isDirectory()) {
19        // Recursively walk-through folders
20        load(fullName);
21      } else if (file.toLowerCase().indexOf('.js')) {
22        // path to JavaScript file
23        let dirs = path.dirname(fullName).split(path.sep);
24
25        if (dirs[0].toLowerCase() === startFolder.toLowerCase()) {
26          dirs.splice(0, 1);
27        }
28
29        //Load the JavaScript file ("controller") and pass the router to it
30        require('./' + fullName)('some funky arguments');
31      }
32    });
33  };
34
35  return {
36    load: load
37  };
38})();
39
40// Boostrap
41loader.load('files');
42module.exports = loader;
43
44
45// =====================================================================
46// files/function1.js
47function fct1(args) {
48    console.log(`running function 1, args: ${args}`)
49};
50module.exports = fct1;

Created on 1/27/2018