Veera
Veera

Reputation: 33182

Node JS - Calling a method from another method in same file

I have this nodeJS code.

module.exports = {

  foo: function(req, res){
    ...
    this.bar(); // failing
    bar(); // failing
    ...
  },

  bar: function(){
    ...
    ...
  }
}

I need to call the bar() method from inside the foo() method. I tried this.bar() as well as bar(), but both fail saying TypeError: Object #<Object> has no method 'bar()'.

How can I call one method from the other?

Upvotes: 15

Views: 24853

Answers (7)

timidboy
timidboy

Reputation: 1722

You can do it this way:

module.exports = {

  foo: function(req, res){

    bar();

  },
  bar: bar
}

function bar() {
  ...
}

No closure is needed.

Upvotes: 14

Nassim
Nassim

Reputation: 2876

in Node js + Express, you can use this syntax in the same controller

//myController.js
exports.funA = () =>{

    console.log("Hello from funA!")

    //cal funB
    funB()

}

let funB = () =>{

    console.log("Hello from funB!")
}

make sure to use the let keyword before the function and call it with the () parentheses inside the main function

OUTPUT

App listening at http://localhost:3000
Hello from fun A!
Hello from fun B!

Upvotes: 0

Nicolas Bonnici
Nicolas Bonnici

Reputation: 460

The accepted response is wrong, you need to call the bar method from the current scope using the "this" keyword:

    module.exports = {
      foo: function(req, res){

        this.bar();

      },
      bar: function() { console.log('bar'); }
    }

Upvotes: 11

Chanaka Fernando
Chanaka Fernando

Reputation: 2335

Try the following code. You can refer each function from anywhere (needs to import .js file)

function foo(req,res){
    console.log("you are now in foo");
    bar();
}
exports.foo = foo;

function bar(){
    console.log("you are now in bar");
}
exports.bar = bar;

Upvotes: 1

user323774
user323774

Reputation: 430

Is bar intended to be internal (private) to foo?

module.exports = {
    foo: function(req, res){
        ...
        function bar() {
            ...
            ...
        }
        bar();     
        ...
    }
}

Upvotes: 1

Lucas Green
Lucas Green

Reputation: 3959

Try this:

module.exports = (function () {
    function realBar() {
        console.log('works');
    }
    return {

        foo: function(){
            realBar();
        },

        bar: realBar
    };
}());

Upvotes: 2

ChaosPandion
ChaosPandion

Reputation: 78262

I think what you can do is bind the context before passing the callback.

something.registerCallback(module.exports.foo.bind(module.exports));

Upvotes: 4

Related Questions