user1547174 user1547174 - 3 months ago 19
Node.js Question

Require multiple api files nodejs

My node.js app is set up where I have an

/app/api
folder, which has several subfolders and subfiles as such:

/app/api/admin/admin_api.js


/app/api/admin/another_admin_api.js


/app/api/general/generic_api.js


/app/api/general/another_generic_api.js


...


Is there a way I can tell my app to use & require ALL of the .js files in
/app/api
?

Thanks in advance!

Answer

The first solution would be to create an index.js in /app/api and export your modules from it.

e.g /app/api/index.js :

const file1 = require('./file1.js');
const file2 = require('./file2.js');

module.exports = {
  file1: file1,
  file2: file2
};

Now when you require the folder /app/api (const api = require('./app/api')) your modules will be available through api.

You also can use something like glob or require-all.