我试图将一组全局变量和函数从一个Javascript文件导出到nodejs中的另一个Javascript文件。
从 的节点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));
但变量;我得到以下输出:
We have imported a global variable with value undefined
and added a constant value to it NaN
为什么 GLOBAL_VARIABLE 导出?
答案 0 :(得分:11)
解决此问题的两种方法:
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
};