S
S
superivankorolev2016-10-05 12:45:53
JavaScript
superivankorolev, 2016-10-05 12:45:53

How to get a nested array of directories?

I am writing a feature for Express. Or for koa.js it doesn't matter.

'use strict'
const fs = require('fs');
let middleware_path = __dirname + '/../middleware/';

var dir = fs.readdirSync(middleware_path);




let middleware = {};  //middleware  автоматическая подгрузка из папки
for(var i=0; i<dir.length; i++){
  if(dir[i].endsWith('.js') && fs.lstatSync(middleware_path+'/'+dir[i]).isFile()){
    dir[i]=dir[i].slice(0, -3); 
    try{
      middleware[dir[i]] = require(middleware_path+dir[i]);
    }catch(e){
      console.log(e);
    }		
  }	
}




module.exports = (router) => {
  router

    .get('/2', middleware.query, function *(next){
      this.body = '<body><script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script></body>';
    })
    


}

In general, now the middleware folder contains query.js
and I conveniently load it with one line .get('/2', middleware.query, function *(next)...
We should do the same, but for the routes folder
, let's say there lies routes/user/login.js
I want to load it like this
.get('/login', routes.user.login)
'use strict';

var path = require('path');
var fs = require('fs');



function getFiles (dirPath, callback) {
    fs.readdir(dirPath, function (err, files) {
        if (err) return callback(err);
        var filePaths = [];
      Promise.all(files.map(function (fileName){
        return new Promise(function(resolve, reject){
          var filePath = path.join(dirPath, fileName);

          fs.stat(filePath, function (err, stat) {
            if (err) return reject(err);

            if (stat.isDirectory()) {
              getFiles(filePath, function (err, subDirFiles) {
                if (err) return reject(err);

                filePaths = filePaths.concat(subDirFiles);
                resolve(null);
              });

            } else {
              if (stat.isFile() && filePath.endsWith('.js')){
                console.log();
                filePaths.push(filePath);
              }

              resolve(null);
            }
          });
        });	
    })).then(results => {
      callback(err, filePaths);
    });

    });
}


getFiles('./', function (err, files) {
    //console.log(err || files);
});

while I coded an asynchronous scan of files in all subdirectories

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2016-10-05
@superivankorolev

Quickly threw a recursion, check for yourself.

scan(middleware_path, middleware);

function scan (dir, d) {
  fs.readdirSync(dir).forEach(function(file) {
    if (fs.statSync(dir + '/' + file).isDirectory()) {
      d[file] = d[file] || {};
      scan(dir + '/' + file, d[file]);
    } else if (file.endsWith('.js') {
      file = file.slice(0, -3); 
      try {
        d[file] = require(middleware_path + file);
      } catch (e) {
        console.log(e);
      }
    }
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question