Require all files in the folder in node.js

When you want all the files in the folder you might think if you give the path of a folder it will fetch all files

in the folder but it doesn't work that way it will look for a file with the name index.js if the file is present it

uses that otherwise the require fails.

If you have control over the folder to create an index.js file and then assign all the modules and require it.


var routes = require("./routes");


exports.something = require("./routes/something.js");

exports.others = require("./routes/others.js");

What if you don't know the file names?! You have to use any loader then.

var normalizedPath = require("path").join(__dirname, "routes");

require("fs").readdirSync(normalizedPath).forEach(function(file) {

require("./routes/" + file);