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!
Written by Mateusz Gachowski
Related protips
4 Responses
 
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
Best
 #Nodejs 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#
 
 
 
