在nodejs中导出变量和函数

Exporting variables and functions in nodejs

本文关键字:变量 函数 nodejs      更新时间:2023-09-26

我正试图在nodejs中将一组全局变量和函数从一个Javascript文件导出到另一个。

发件人节点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

解决此问题的两种方法:

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