Trung Tran
Trung Tran

Reputation: 13741

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!

Upvotes: 1

Views: 599

Answers (2)

Léo Martin
Léo Martin

Reputation: 746

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.

Upvotes: 2

Pramod Jangam
Pramod Jangam

Reputation: 336

You can use Browsing.js or https://www.npmjs.com/package/bundle-up2 based on your requirements. Although I would recommend not bundling if you are working on API side of nodejs for sake of readability. Browsify should fit your requirement if you are working on client side scripting.

Upvotes: 1

Related Questions