Categories
JavaScript Answers

How to require all files in a folder with Node.js?

Spread the love

Sometimes, we want to require all files in a folder with Node.js.

In this article, we’ll look at how to require all files in a folder with Node.js.

How to require all files in a folder with Node.js?

To require all files in a folder with Node.js, we can create an index.js file that exports all the files we want to require.

Then we can require the index.js file.

For instance, we write

routes/index.js

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

to export the ./routes/something.js and ./routes/others.js modules.

Then we can require the routes/index.js file with

app.js

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

routes has the something and others properties.

routes.something references require("./routes/something.js") and routes.others references require("./routes/others.js").

Conclusion

To require all files in a folder with Node.js, we can create an index.js file that exports all the files we want to require.

Then we can require the index.js file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *