在nodejs中导出variables和函数
我试图将一组全局variables和函数从一个Javascript文件导出到nodejs中的另一个。
从node-js.include.js
var GLOBAL_VARIABLE = 10; exports.GLOBAL_VARIABLE = GLOBAL_VARIABLE; module.exports = { add: function(a, b) { return a + b; } };
到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));
但variables; 我得到以下输出:
We have imported a global variable with value undefined and added a constant value to it NaN
为什么不是GLOBAL_VARIABLE输出?
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 };