16

I wish to split a large configuration .js file into multiple smaller files yet still combine them into the same module. Is this common practice and what is the best approach so that the module would not need extending when new files are added.

An example such as but not needing to update math.js when a new file is added.

math - add.js - subtract.js - math.js

// add.js
module.exports = function(v1, v2) {
    return v1 + v2;
}

// subtract.js
module.exports = function(v1, v2) {
    return v1 - v2;
}

// math.js
var add = require('./add');
exports.add = add;

var subtract = require('./subtract');
exports.subtract = subtract;

// app.js
var math = require('./math');
console.log('add = ' + math.add(5,5));
console.log('subtract =' + math.subtract(5,5));
rjinski
  • 615
  • 1
  • 7
  • 12
  • 4
    possible duplicate of [node.js require all files in a folder?](http://stackoverflow.com/questions/5364928/node-js-require-all-files-in-a-folder) – Bergi May 09 '14 at 11:42
  • All the searching in the world and I didn't find that. Thank you. – rjinski May 09 '14 at 12:20

4 Answers4

9

You can use the spread operator ... or if that doesnt work Object.assign.

module.exports = {
   ...require('./some-library'),
};

Or:

Object.assign(module.exports, require('./some-library'));
Kevin Upton
  • 3,336
  • 2
  • 21
  • 24
6

If your NodeJs allows the spread (...) operator (check it here), you can do:

    module.exports = {
        ...require('./src/add'),
        ...require('./src/subtract')
    }
kedoska
  • 173
  • 1
  • 7
  • ... and if it doesn't? – Chad Jan 26 '18 at 00:47
  • @chad, an option is probably to write javascript ES6 and use babel (or others) to produce ES5 and run it with the old node.js. – kedoska Jan 31 '18 at 04:17
  • Object.assign has always been the way to do this before spread operator. `module.exports = Object.assign({}, require('./src/add'), require('./src/subtract'));` – Apolo Jun 09 '20 at 15:28
2

You can do this

// math.js 
module.exports = function (func){
    return require('./'+func);
}

//use it like this 
// app.js

var math = require('./math');
console.log('add = ' + math('add')(5,5));
console.log('subtract =' + math('subtract')(5,5));
kerolos
  • 127
  • 1
  • 2
  • 10
2

You could create a subfolder to assign functions and other objects automaticly.

mymodule.js

const pluginDir = __dirname + '/plugins/';
const fs = require('fs');

module.exports = {};

fs.readdirSync(pluginDir).forEach(file => {
    Object.assign(module.exports,require(pluginDir + file));
});

plugins/mymodule.myfunction.js

module.exports = {

    myfunction: function() {
        console.log("It works!");
    }

};

index.js

const mymodule = require('mymodule.js');

mymodule.myfunction();
// It works!
Dennis Bohn
  • 121
  • 1
  • 5