7

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

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
userMod2
  • 8,312
  • 13
  • 63
  • 115

3 Answers3

5

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
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
1

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()
skylize
  • 1,401
  • 1
  • 9
  • 21
  • I need to use it in the same file – userMod2 Aug 30 '17 at 06:05
  • I updated this response, I made a clear mistake in my original answer. – skylize Aug 30 '17 at 06:13
  • Also, here's a fun variant that you shouldn't actually use because it will bewilder anyone else trying to reading your code. Once you've assigned a function to `module.exports`, just call `module.exports();` to run it. =P – skylize Aug 30 '17 at 06:17
1
var func = module.exports = myFunction(){
   //do some stuff here
}

Now you can access through variable.

aaqib90
  • 510
  • 1
  • 5
  • 16