简体   繁体   中英

Multiple module.exports for NodeJS

I was trying to add two module.exports in my NodeJS module. 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:

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. 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. You will need to put the one method on your main function.

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=... ). Then you reassing the whole module.exports object with the second line and thus erasing the first function you asssinged to it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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