maroodb
maroodb

Reputation: 1118

How to call an exported function internally in nodejs?

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

Upvotes: 1

Views: 643

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

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.

Upvotes: 3

Related Questions