Last Updated: February 25, 2016
·
22.39K
· mateuszgachowski

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!

4 Responses
Add your response

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

over 1 year ago ·

Happy to help :) Cheers.

over 1 year ago ·

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 ·

Hi danilodeveloper,

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

Cheers,
Mateusz

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside