2016-07-25 216 views
1

我想將一組全局變量和函數從一個Javascript文件導出到nodejs中的另一個。在nodejs中導出變量和函數

節點js.include.js

var GLOBAL_VARIABLE = 10; 

exports.GLOBAL_VARIABLE = GLOBAL_VARIABLE; 

module.exports = { 

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

}; 

測試節點-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)); 

但是變量;我得到以下輸出:

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

爲什麼不GLOBAL_VARIABLE出口?

+0

[module.exports VS在Node.js的出口(的可能的複製http://stackoverflow.com/questions/7137397/module -exports-VS-出口,在節點-JS) –

回答

6

2種方法來解決這個問題:

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