0

How can I get all the js files that are inside of folder, and that folder is inside of another folder?

I'm very new to JS, and I know I can get it using readdirSync but I can only get all the files in the current directory.

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    console.log(file + "✅"); 
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Here's my file structure.

enter image description here

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Glenn Posadas
  • 12,555
  • 6
  • 54
  • 95

1 Answers1

2

This can be solved with glob. It’s a package but allows for finding files at any level.

var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})
Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • You helped me a lot by introducing the module `glob`. :) BUT, I spent around 51mins+ figuring out the pattern, plus I didn't realize so soon that my `const model...` makes the final path incorrect. For the record, here's my path, just in case in the future, some newbie js person like me finds this. ```const files = glob.sync(__dirname + "/*/*.js")``` – Glenn Posadas May 08 '20 at 20:00