1

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?

2

1 Answer 1

2
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.