0

I'm looking to import/export a list of files in a directory through an index.js file in the same directory.

For example, I have 2 files in a directory: admin.js and user.js and I am looking to require and exporting them in the in the index.js like so

module.exports = {
  admin: require("./admin"),
  users: require("./users"),
};

The script I have come up with looks like this but it is not working and giving me an error

fs.readdirSync(__dirname, (files) => {
  files.forEach((file) => {
    module.exports[file] = require(`./${file}`);
  });
});

How can I improve this script to make it work?

Thank you!

[Update - 2022 December 18]

Found a solution based off of sequelize models/index.js, this will pretty much require and export your files and folders, feel free to use and modify

const fs = require('fs')
const path = require('path')
const basename = path.basename(__filename)
const controllers = {}

fs.readdirSync(__dirname)
  .filter((folder) => {
    return folder.indexOf('.') !== 0 && folder !== basename
  })
  .forEach((folder) => {
    const controller = require(path.join(__dirname, folder))
    controllers[controller.name] = controller
  })

module.exports = controllers
3
  • not working and giving me an error. Please provide the exact error message and describe what isn't working. This is general advice for any problem you post about here. Commented Nov 28, 2022 at 23:47
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Nov 29, 2022 at 3:51
  • Hey, you can add your solution as an answer Commented Dec 9, 2022 at 11:48

1 Answer 1

1

fs.readdirSync() does NOT accept a callback. It directly returns the result:

const files = fs.readdirSync(__dirname);
for (let file of files) {
    module.exports[file] = require(`./${file}`);
}

Note, the future of the Javascript language is using import and export with statically declared module names instead of require()and module.exports and this structure will generally not work with the newer way of doing things. So, if you expect to eventually move to the newer ESM modules, you may not want to bake in this type of architecture.

There is a dynamic import in ESM modules, but it's asynchronous (returns a promise that you have to wait for).

Also, note that this will attempt to reload your index.js file containing this code. That's might not be harmful, but may not be your intention.

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

2 Comments

I attempted your solution but got this error throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) TypeError: Router.use() requires a middleware function but got a undefined Here is how I am importing it in the other file, const { admin, users } = require("./router");
@R41313IT - That error does not come from the code in my answer or your question. It comes from something further upstream/downstream and it also depends upon what is being exported in the actual module files you're loading. We can't figure out what is causing that without seeing ALL the code involved. That particular error means you are passing a non-function to router.use().

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.