简体   繁体   English

NodeJS的多个module.exports

[英]Multiple module.exports for NodeJS

I was trying to add two module.exports in my NodeJS module. 我试图在我的module.exports模块中添加两个module.exports I tried below code for my module: 我为模块尝试了以下代码:

exports.one = function(data){
    const one = data;
};
module.exports = function(msg) {
    console.log(one+'::'+msg);
};

And below code for index.js: 下面是index.js的代码:

var myModule = require('./mymodule.js');


myModule.one('hi');
myModule('bro');
myModule('Dear');
myModule('Dude');

I was expected that it will log below data into the console: 我预期它将以下数据记录到控制台中:

hi bro
hi Dear
hi Dude

But the console says: 但是控制台说:

TypeError: myModule.one is not a function
    at Object.<anonymous> (....

Please how do I solve this issue? 请如何解决这个问题? There are Stack Overflow questions asking how to use multiple module.exports in NodeJS modules. 还有一些堆栈溢出问题,询问如何在NodeJS模块中使用多个module.exports。 But the answer is something like below: 但是答案如下:

exports.one = function (){};
exports.two = function (){};

But if I use that code, I have to use 但是,如果我使用该代码,则必须使用

myModule.one('hi');
myModule.two('bro');
myModule.two('Dear');
myModule.two('Dude');

Instead of: 代替:

myModule.one('hi');
myModule('bro');
myModule('Dear');
myModule('Dude');

You seem to be looking for 您似乎在寻找

let one = '';
module.exports = function(msg) {
    console.log(data+'::'+msg);
};
module.exports.one = function(data){
    one = data;
};

Notice that the exports variable is just an alias for the module.exports object, and when overwriting that with your function you threw away its contents. 注意, exports变量只是module.exports对象的别名,当用函数覆盖它时,您将其内容丢弃。 You will need to put the one method on your main function. 您将需要在主函数上放置one方法。

When you do the following: 当您执行以下操作时:

module.exports.one = function(data){
    const one = data;
};
module.exports = function(msg) {
    console.log(data+'::'+msg);
};

You first assign the property one to the module object ( exports.one=... ). 首先,将属性一个分配给模块对象( exports.one=... )。 Then you reassing the whole module.exports object with the second line and thus erasing the first function you asssinged to it. 然后,用第二行重新设置整个module.exports对象,从而擦除您赋予它的第一个功能。

You can solve it like this: 您可以这样解决:

module.exports.one = function(data){
    const one = data;
};
module.exports.two = function(msg) {
    console.log(data+'::'+msg);
};

Then you can call the functions in your other module like this: 然后,您可以像下面这样调用其他模块中的函数:

var myModule = require('./mymodule.js');
myModule.one(arg1) // calls first function
myModule.two(arg2) // calls second function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM