2

I'm trying to export a set of global variables and functions from one Javascript file to another in nodejs.

From node-js.include.js

var GLOBAL_VARIABLE = 10;

exports.GLOBAL_VARIABLE = GLOBAL_VARIABLE;

module.exports = {

    add: function(a, b) {
        return a + b;
    }

};

into test-node-js-include.js:

var includes = require('./node-js-include');

process.stdout.write("We have imported a global variable with value " + includes.GLOBAL_VARIABLE);

process.stdout.write("\n and added a constant value to it " + includes.add(includes.GLOBAL_VARIABLE, 10));

but the variable; I get the following output:

We have imported a global variable with value undefined
 and added a constant value to it NaN

why isn't GLOBAL_VARIABLE exported?

Sebi
  • 4,262
  • 13
  • 60
  • 116
  • Possible duplicate of [module.exports vs exports in Node.js](http://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js) – Ben Fortune Jul 25 '16 at 15:39

1 Answers1

11

2 ways to fix this:

module.exports.GLOBAL_VARIABLE = GLOBAL_VARIABLE;

module.exports.add: function(a, b) {
    return a + b;
};

module.exports.GLOBAL_VARIABLE = GLOBAL_VARIABLE;

module.exports = { 
    add: function(a, b) {
        return a + b;
    }, 
    GLOBAL_VARIABLE: GLOBAL_VARIABLE
};
Naftali
  • 144,921
  • 39
  • 244
  • 303