Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js require all files in a folder?

How do I require all files in a folder in node.js?

need something like:

files.forEach(function (v,k){   // require routes   require('./routes/'+v); }}; 
like image 363
Harry Avatar asked Mar 19 '11 21:03

Harry


People also ask

For what require () is used in Node JS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

Can we use import instead of require in node JS?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel. As always, if you have any questions, feel free to leave a comment.

Should I use import or require in NodeJS?

NOTE: You must note that you can't use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program.


1 Answers

When require is given the path of a folder, it'll look for an index.js file in that folder; if there is one, it uses that, and if there isn't, it fails.

It would probably make most sense (if you have control over the folder) to create an index.js file and then assign all the "modules" and then simply require that.

yourfile.js

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

index.js

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

If you don't know the filenames you should write some kind of loader.

Working example of a loader:

var normalizedPath = require("path").join(__dirname, "routes");  require("fs").readdirSync(normalizedPath).forEach(function(file) {   require("./routes/" + file); });  // Continue application logic here 
like image 147
tbranyen Avatar answered Oct 30 '22 14:10

tbranyen