Search code examples
javascriptnode.jsrequire

Node.js `require` into an array instead of a variable


It is possible to var x = require('x.js') and use x later on to access all the nice stuff. What is the closest way to build an array of required things, like:

var xs = [require('a.js'), require('b.js')]

and then access the exported features as xs[0].feature and xs[1].feature?


Solution

  • Unless you have very good reason to do this, it should probably be avoided. But it can be done quite simply using Array.prototype.map().

    var xs = ['foo.js', 'bar.js', 'baz.js'].map(require);