f3qtoa
Last Updated: February 25, 2016
·
10.65K
· mateuszgachowski
Avatar

Node.js - How to load modules recursively from directory

Quick how-to load files in node.js as modules.

index.js:

require('fs').readdirSync(__dirname).forEach(function (file) {
  /* If its the current file ignore it */
  if (file === 'index.js') return;

  /* Store module with its name (from filename) */
  module.exports[path.basename(file, '.js')] = require(path.join(__dirname, file));
});

ping.js (example module):

module.exports = (function (params, request) {
  broadcastUser({data: 'pong'}, 'message', request);
});

Thats all!

Say Thanks
Respond

4 Responses
Add your response

14572
814a06889caf7ade092db4f537a9f6ed

Sometimes I forget the __dirname shortcuts. Thanks for reminding me :-)

over 1 year ago ·
14607
Avatar

Happy to help :) Cheers.

over 1 year ago ·
15665
A0ddc0192ae3b516c0055b270e026bcc

Hello Mateus!
I don't understood why is needed the use of _.extend(module.exports, mod);
Would be great you explain for me :)

over 1 year ago ·
15666
Avatar

Hi danilodeveloper,

You are right, there is no need. Ill change it, thanks for clever eye :)

Cheers,
Mateusz

over 1 year ago ·