1

How can create a function that is only used in mymodule.js

but is also accessible from outside mymodule.js

Of course i could also do:

module.exports = {
  myfunction: function() {
    return "HELLO";
  },

};

But isnt there a way to declare a function once and export it later?

mymodule.js:

var x = function P(inp) {

    console.log('P');

}

module.exports = {
    method: x(),
}

other.js:

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

mac.x(); //<-- does not work
Bob
  • 167
  • 1
  • 1
  • 8
  • Possible duplicate of [Using exports in nodejs to return a value](http://stackoverflow.com/questions/42352348/using-exports-in-nodejs-to-return-a-value) –  Feb 21 '17 at 14:34

1 Answers1

2

In mymodule.js:

function P(inp) { // you may or may not declare it with "var x ="..both are valid
    console.log('P');
}

module.exports = {
    method: P // "method" is the name by which you can access the function P from outside
};

In other.js:

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

mac.method(); // Call it by the name "method"

If you want you can also keep the same name. ie., in mymodule.js:

module.exports = {
    P: P // In this case, "P" is the name by which you can access the function P from outside
};

You can also export it like this:

exports.P = P; // This has the same effect as above example

Or:

module.exports.P = P; // This has the same effect as above example

However, if you want to export only one function from mymodule.js then you can do what @LucaArgenziano suggested, like this:

In mymodule.js:

function P(inp) {
    console.log('P');
}

module.exports = P;

In other.js

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

mac();
Community
  • 1
  • 1
Soubhik Mondal
  • 2,666
  • 1
  • 13
  • 19
  • 2
    If you're exporting only one function outside of a JS file there's no need to add all this fields to the `module.exports` object. You can simply do `module.exports = P;`. By design the node.js method `require` looks for `module.exports` inside the target file and returns it. In this case, doing something like: `var mac = require('./mac.js'); mac();` makes much more sense in my opinion. – Luca Argenziano Feb 21 '17 at 15:44
  • @LucaArgenziano i agree. I'll add it to my answer – Soubhik Mondal Feb 21 '17 at 16:04