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

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.