1

I have a collection of helper functions and i like to merge them together with already existing utility modules.

Somehow like this:

var customUtil = require('customUtilites');
customUtil.anotherCustomFunction = function() { ... };

exports = customUtil;

Can this be achieved somehow?

zaphod1984
  • 836
  • 2
  • 7
  • 22

1 Answers1

2

You can totally do so.

e.g.

customUtilities.js:

module.exports = {
  name: 'Custom'
};

helperA.js

module.exports = function() {
  console.log('A');
}

helperB.js:

module.exports = function() {
  console.log('B');
}

bundledUtilities.js:

var customUtilities = require('./customUtilities');

customUtilities.helperA = require('./helperA');
customUtilities.helperB = require('./helperB');

module.exports = customUtilities;

main.js:

var utilities = require('./bundledUtilities');
utilities.helperA();

run node main.js you will see A printed.

qiao
  • 17,941
  • 6
  • 57
  • 46
  • I recommend not modifying the original module. It can break stuff that depend on it. Instead, copy it into a new object and modify that. – fent Jan 16 '12 at 19:27
  • Thanks, works like a charm! I always wrote `exports = {...}` that don't work, `module.exports = {...}` is working. I have no idea why `exports = {...}` returns a empty result while `module.exports = {...}` works fine. @DeaDEnD I see your point, in my case I want to add this function to a preexisting library: `exports.compatFileSeperator = function() { return process.platform === 'win32' ? '\\' : '/'; };` since I'm currently developing on Win7 but also want to deploy on a unix like systems. – zaphod1984 Jan 16 '12 at 20:06
  • @zaphod1984 It's a common mistake :) you may check out http://stackoverflow.com/questions/6116960/what-do-module-exports-and-exports-methods-mean-in-nodejs for the differences between `exports` and `module.exports`. – qiao Jan 17 '12 at 04:59
  • @qiao thankyou for the link. its a bit missleading that even in the official documentation ([link](http://nodejs.org/docs/v0.4.8/api/modules.html) see the circles example) that style is used. which works fine vor methods but not for entire objects... :) anyway thanks a lot, i think i'm happy now. – zaphod1984 Jan 17 '12 at 09:43