This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                                5年前关闭。
            
                    
我已经写了这个功能。它的工作是将所有文件递归地读取到一个文件夹中,这要归功于nodejs模块recursive-readdir。它运作良好。
问题是我不知道如何使用routes导出到module.exports数组之外。我试图把它放在回调函数的外面,但是里面的变量是不确定的。任何想法?

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]);
    }
  }
});

最佳答案

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); }
});


您现在可以像这样使用它

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




如果您想要更富有表现力的方式,您可能想要做

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


然后在外面使用

var routes = require('routes')
routes.find(function (routes) {...});

10-06 00:02