1

I have written this function. What it does is reading recursively all the files into a folder thanks to nodejs module recursive-readdir. It works well. The problem is I don't know how to export outside routes array by using module.exports. I have tried to put it outside the callback function, inside but the variable is undefined. Any idea?

var path = require('path');
var recursive = require('recursive-readdir');

recursive(__dirname, function(err, files){

  var routes = {};

  for (var i = 0, dim = files.length; i < dim; i++) {
    var file = path.basename(files[i], '.js');
    if(file !== 'bootstrap'){
      routes[file] = require(files[i]);
    }
  }
});
Mazzy
  • 13,354
  • 43
  • 126
  • 207

1 Answers1

2
var path = require('path');
var recursive = require('recursive-readdir');

module.exports = function getRoutes(callback) {
     recursive(__dirname, function(err, files){

         var routes = {};

         for (var i = 0, dim = files.length; i < dim; i++) {
             var file = path.basename(files[i], '.js');
             if(file !== 'bootstrap'){
                 routes[file] = require(files[i]);
             }
         }

         if (callback) { callback(routes); }
});

you can now use it like this

require('get_routes')(function(routes) { ... }); 

.

if you want more expressive way you may want to do

module.exports.find = function (callback) { ... }

then outside use

var routes = require('routes')
routes.find(function (routes) {...});
Barak
  • 1,148
  • 7
  • 13
  • Ok inside function(routes) { ... } I could take routes values. Do you think it is a best practice? Do you know any other best way ? – Mazzy Aug 18 '14 at 22:37
  • when you use anything async you have to use callbacks, there is a pattern called promise which may make more sense for you, but at the end you will have to provide a function to be called in a future time. http://www.html5rocks.com/en/tutorials/es6/promises/#toc-async – Barak Aug 18 '14 at 23:19
  • your other way will be to avoid recursive-readdir and run the recursion yourself using sync reads. It may actually make more sense since you are trying to require it after all. If it's done once on startup you can let yourself block the thread until the recursion is finished. – Barak Aug 18 '14 at 23:23
  • yes in fact I have just fixed it by using read sync recursion. Now it works. After all it will be executed only once at the startup of the server. Anyway thank you very much for your article you have suggested me – Mazzy Aug 18 '14 at 23:25