Node.js将函数导出为文件之间的变量或对象

Node.js exports a function as a variable or object between files

本文关键字:之间 变量 对象 文件 js 函数 Node      更新时间:2023-09-26

在moudle1.js中,我将模块导出为对象。

  module.exports = {
           attribute1: function(param1, param2) {
                   attribute2(param1);
                   attribute3(param2)
            }
           attribute2 : function(param) {
           }
           attribute3 : function(param1) {
           }
    };

在module2.js中,我希望能够

var module1 = require('./module1');
exports.module1 = module1.attribute1;
exports.module1 = module1.attribute2;

请注意,我不是故意写module1.attribute1(param1,param2)的。我不想在这个文件中给出参数,但在第三个文件中,我可以

var module2 = require('./module2');
var param1 = 'foo';
var param2 = 'dummy';
module.module1(param1,param2);

这主要是为了测试。

您实际上可以导出函数本身,而不是对象。

此外,请不要将function用作变量名,这是一个保留字。

// function.js
module.exports = function (param1, param2) {...}

// module.js
var fn = require('./module');
fn('foo', 'dummy')

创建一个与您的文件相同的文件module1.js

module.exports = {
           attribute1: function(param1, param2) {
                   attribute2(param1);
                   attribute3(param2)
            }
           attribute2 : function(param) {
           }
           attribute3 : function(param1) {
           }
    };

创建另一个文件并将其命名为"index.js"

在文件中,将内容保存为

module.exports = {
     module1 : require('./module1').attribute1
     module2 : require('./module1').attribute2
     module3 : require('./module1').attribute3
}

将两个文件都保存在一个文件夹中,并将其命名为"module".

导出要使用功能的文件夹名称

var module = require('./module')

并使用功能

module.module1("foo""bar");