Salman Fazal
Salman Fazal

Reputation: 587

Not able to call functions from another JS file

Got this really simple problem that I just can't figure a solution to. I am not able to call a function from another javascript file in nodejs.

My main file:

var Binance = require('./binance.js');

//later in the file
app.post('/createBotOrder', function (req, res, next) {
    console.log("in");
    console.log(Binance);
    console.log(Binance.sum(1, 2));
    console.log("in 2");
});

My secondary file:

module.exports = function() {
    this.sum = function(a,b) { return a+b };
    this.multiply = function(a,b) { return a*b };
    //etc
}

Output:

in
[Function]

Upvotes: 0

Views: 1551

Answers (2)

Quentin
Quentin

Reputation: 943207

Binance is a constructor function. It doesn't have a sum property.

When you call Binance, then it assigns a function to the sum property of this.

You aren't calling Binance at all.

Thus:

var Binance = require('./binance.js');
var my_binance = new Binance();

//later in the file
app.post('/createBotOrder', function (req, res, next) {
    console.log("in");
    console.log(my_binance);
    console.log(my_binance.sum(1, 2));
    console.log("in 2");
});

That said, it doesn't make sense for Binance to be a constructor function. There's nothing to distinguish one instance of it from another. You might as well export a simple object:

module.exports = {
    this.sum = function(a,b) { return a+b },
    this.multiply = function(a,b) { return a*b },
};

and then:

var binance = require('./binance.js');

//later in the file
app.post('/createBotOrder', function (req, res, next) {
    console.log("in");
    console.log(binance);
    console.log(binance.sum(1, 2));
    console.log("in 2");
});

Note that variable names starting with a capital letter are traditionally reserved for constructor functions. Since it isn't a constructor function, I renamed it.

Upvotes: 3

GifCo
GifCo

Reputation: 1363

You want to export as an object with your function as a property.

module.exports = { myFunc : function () { //stuff } }

Then in the file where you import myFunc

const Binance = require('./binance.js')
Binance.myFunc()

Upvotes: 5

Related Questions