N
N
Nicholas2016-01-18 07:48:07
Node.js
Nicholas, 2016-01-18 07:48:07

How to get a list of js files in a folder and subfolders in node js?

How to get a list of js files in a folder and subfolders in node js?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Prozorov, 2016-01-18
@Staltec

Asynchronously (and sequentially) it looks a bit more fun:

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


function getFiles (dirPath, callback) {

    fs.readdir(dirPath, function (err, files) {
        if (err) return callback(err);

        var filePaths = [];
        async.eachSeries(files, function (fileName, eachCallback) {
            var filePath = path.join(dirPath, fileName);

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

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

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

                } else {
                    if (stat.isFile() && /\.js$/.test(filePath)) {
                        filePaths.push(filePath);
                    }

                    eachCallback(null);
                }
            });
        }, function (err) {
            callback(err, filePaths);
        });

    });
}


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

UPD: Added a file extension check so that only *.js files get into the list

N
Nicholas, 2016-01-18
@ACCNCC

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

var getFiles = function (dir, files_){
    
  files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
};

console.log(getFiles('/home/Project/hello/www'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question