Reputation: 43833
In my node.js app, I load modules from a folder, and put them in an array. Right now I do it manually like this
var sitesList = [
require('./js/sites/A.js'),
require('./js/sites/B.js'),
require('./js/sites/C.js')
];
but over time, I don't want to add the file name to this list everytime I add a new module. How can I just loop through all js files in the sites folder and auto add them in an array?
Upvotes: 1
Views: 3207
Reputation: 121
var normalizedPath = require("path").join(__dirname, "js/sites");
var sitesList = [];
var fs = require("fs");
fs.readdirSync(normalizedPath).forEach(function(file) {
sitesList.push(require("./js/sites/" + file));
});
you can also look into this module:
https://github.com/felixge/node-require-all
Upvotes: 2