1

I am trying to call an exported function inside the nodejs module.

exports.sayHello = function (msg) {
 console.log(msg) 
}

function run(msg) {
  this.sayHello(msg);
}

run("hello");

when I run this script I got TypeError: this.sayHello is not a function

maroodb
  • 1,026
  • 2
  • 16
  • 28
  • I'm curious why after assigning a function to `exports.sayHello`, it did not occur to you to call it via `exports.sayHello()`? That's where you assigned the function, that's where you can access it. – jfriend00 Jun 16 '18 at 14:35

1 Answers1

3

Simply declare it separately from exporting it (and don't use this when calling it, you haven't attached it to an object):

function sayHello(msg) {
 console.log(msg) 
}
exports.sayHello = sayHello;

function run(msg) {
  sayHello(msg);
}

run("hello");

That said, you could call it via exports:

exports.sayHello = function (msg) {
 console.log(msg) 
}

function run(msg) {
  exports.sayHello(msg); // <===
}

run("hello");

...but that seems a bit roundabout to me, though I'm told it can help with testing, such as in this example.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This is not a roundabout if it serves a purpose, e.g. improves testability. – Estus Flask Jun 16 '18 at 13:37
  • If module exports are consistently called as `exports` methods, it's possible to spy or mock them. This improves testability in cases like this one, https://stackoverflow.com/questions/50854440/spying-on-an-imported-function-that-calls-another-function-in-jest . Of course, this won't work for this particular `run` function. – Estus Flask Jun 16 '18 at 13:42
  • @estus - I think you probably have more experience with that than I do. I've updated that comment, thanks! – T.J. Crowder Jun 16 '18 at 13:48