node.jsfsgetfiles

Get all files recursively in directories NodejS


I have a little problem with my function. I would like to get all files in many directories. Currently, I can retrieve the files in the file passed in parameters. I would like to retrieve the html files of each folder in the folder passed as a parameter. I will explain if I put in parameter "test" I retrieve the files in "test" but I would like to retrieve "test / 1 / *. Html", "test / 2 / . /.html ":

var srcpath2 = path.join('.', 'diapo', result);
function getDirectories(srcpath2) {
                return fs.readdirSync(srcpath2).filter(function (file) {
                    return fs.statSync(path.join(srcpath2, file)).isDirectory();
                });
            }

The result : [1,2,3]

thanks !


Solution

  • It looks like the glob npm package would help you. Here is an example of how to use it:

    File hierarchy:

    test
    ├── one.html
    └── test-nested
        └── two.html
    

    JS code:

    const glob = require("glob");
    
    var getDirectories = function (src, callback) {
      glob(src + '/**/*', callback);
    };
    getDirectories('test', function (err, res) {
      if (err) {
        console.log('Error', err);
      } else {
        console.log(res);
      }
    });
    

    which displays:

    [ 'test/one.html',
      'test/test-nested',
      'test/test-nested/two.html' ]