Easier module imports with Requiredir

The more that I use Node.js, the more I enjoy it; however, there I have seen an issue in a couple of projects.  In these projects, some modules import in a large number of other modules that reside in single directory.  While it could be argued that the code could be refactored differently, scenarios exist where you may need to import in a number of modules that all exist in the same directory.

Enter Requiredir()

To address this scenario, I created requiredir (npm, github).  Where as Node’s require() function imports in a single module, requiredir() will import in a directory’s worth of modules using a similar syntax.

var requiredir = require("requiredir");
var routes = require("./routes");

The above snippet provides will import in all modules located in the ./routes directory.  When each module is imported, it becomes a named property on the (in this example) routes object.  So, if we had a module that managed all routes for the product pages and the customer pages of a site, those modules could be accessed in the following way.

var productRoutes = routes.products;
var customerRoutes = routes.customers;

At this point, you can use each module as if you had called require() for each individually.  However, there are a few additional features for requiredir().

var moduleCount = routes.length;
var routeArray = routes.toArray();

There may come a scenario when you want to sequentially access modules that were imported in a fashion similar to an Array. For this reason, I added the toArray() function and use it in my migration utility that I’ll write about next.

Other Details

While that’s pretty much all there is to know about requiredir, there are two other things I need to point out.

  1. It does not import modules or any file whose filename starts with a ‘.’ (i.e. hidden files on Mac and Linux).
  2. requiredir() does not do a recursive import. If you have directories within directories that need to be imported, those will need to be a separate require() or requiredir() depending on your situation.

Beyond all of that, the only thing left is to simply install it from npm and have some fun with it.

npm install requiredir

My next post will be talking about Monarch my migration utility that uses this requiredir module. So if you are looking for an example of how requiredir is in use, stay tuned.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close