javascript - Node.js `require` into an array instead of a variable - Stack Overflow

admin2025-04-20  0

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?

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?

Share Improve this question asked Jul 3, 2016 at 21:39 alisianoialisianoi 2,3933 gold badges35 silver badges49 bronze badges 2
  • @JordanHendrix yes, it does not work. So, I am asking for the closest similar way to do it. – alisianoi Commented Jul 3, 2016 at 21:40
  • 1 @JordanHendrix alright, half an hour later I see that I must have made a mistake and it is indeed possible to require an array of things. – alisianoi Commented Jul 3, 2016 at 22:10
Add a ment  | 

3 Answers 3

Reset to default 5

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);

Perhaps you can do something like this:

var x = [];
var requiredLibraries = ['a.js', 'b.js', 'c.js'];

requiredLibraries.forEach(function(element, index, array) {
    x.push(require(element));
});

EDIT Please note that I don't think this is a good idea, because of confusion it might bring and lower the readability of your code, if nothing else.

Both getRoutes and postRoutes are files .js (getRoutes.js and postRoutes.js)

I used this approach to create an index.js with all my routes.

index.js

const routes = [require("./getRoutes"), require("./postRoutes")];

module.exports = { routes };

// OR

const routes = ["./getRoutes", "./postRoutes"].map(require);

module.exports = { routes };

getRoutes.js and postRoutes.js they would look something like that

const express = require("express");
const router = express.Router();
const { users } = require("../controllers");

router.post("/user", users);

module.exports = router;
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745123306a286276.html

最新回复(0)