Answer the question
In order to leave comments, you need to log in
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>';
})
}
.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);
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question