userMod2
userMod2

Reputation: 8960

JS - How to access a module.exports function in the same file

I have a function that looks like:

module.exports = myFunction() {
  //do some stuff
}

I can access it fine from other file using var myFunction = require(.thepath.js)

However how can i access it from the file that it was created.

I've tried myFunction() and this.myFunction() but neither work.

Thanks

Upvotes: 7

Views: 6830

Answers (3)

skylize
skylize

Reputation: 1421

You could actually use an anonyomous function here if you didn't want to call it in the same file

module.exports = function (){
    // do some stuff
}

As long as you give it a name, you can just call it by using its name.

module.exports = function myFunction(){

// do some stuff }

myFunction()

Sorry, I remembered this incorrectly. There is a scoping problem here that can be solved by defining the function seperately from the assignment.

function myFunction (){
    // do some stuff
}
module.exports = myFunction

myFunction()

Upvotes: 1

aaqib90
aaqib90

Reputation: 548

var func = module.exports = myFunction(){
   //do some stuff here
}

Now you can access through variable.

Upvotes: 1

Get Off My Lawn
Get Off My Lawn

Reputation: 36289

You can save it to a variable then export the variable like so:

// Create the function
const myFunction = function() {

}

// Call the function
myFunction();

// Export the function
module.exports = myFunction

Upvotes: 5

Related Questions