UPDATE: better-require now supports json, yaml, csv, xml, ini as well as coffeescript, clojurescript, typescript, dart and six.

While reading the Node.js API documentation today, I stumbled upon an interesting feature. This feature let’s you add handlers for arbitrary file extensions that require() will call when requiring a file of that extension. Internally, it looks for the extension in require.extensions and if the extension is found, the handler is called instead of the default require routine.

I thought that was pretty cool so I couldn’t resist the urge of wrapping a bunch of file parsers into a standalone NPM module that would make it easy to support for multiple file formats through require().

This gave birth to better-require.

npm install better-require

If allows developers to seamlessly require json, yaml, csv, xml and ini files without having to deal with require.extensions or finding the appropriate parsing libraries. It is also easily extensible so feel free to fork and add additional file formats!

Here’s a usage example:

require('better-require')('json yaml xml');

// we can now require .xml, .yaml and .xml files!

var yaml = require('./config.yaml')
  , json = require('./config.json')
  , xml = require('./config.xml');