简体   繁体   中英

Why does my Basic function is not working (in NodeJS)?

I'm working on a nodejs project and there is a little problem. I know the problem is not hard to solve but i've been searching for hours now and still didn't figure out how to solve it :

var gs = require('./gs1');
if (uncompressedDigitalLinkInput != "") {
    try {
        this.error3="";
        console.log("Test");
        gs.myfunction();
    } 
    catch(err) {
        this.error3=err+"\n"+err.stack;
        return "";
    }
} 
else {
    return "";
}

And the problem is the line :

console.log("Test");
gs.myfunction();

Indeed, out of these two, only the console.log work. The other one doesn't.

Here is the code of "gs.myfunction"

class GS1DigitalLinkToolkit {
    function myfunction(){
        console.log('Function called');
    }
}
module.exports.myfunction = myfunction;

It tells me that "gs.myfunction is not a function". I have made sure that the require is the right path. So why it isn't working?

It happens because the method is callable only by an instance of GS1DigitalLinkToolkit. Two possible solutions can be:

1) Make the method static and export it as

class GS1DigitalLinkToolkit {
  static myfunction() {
      console.log('Function called');
  }
}

module.exports.myfunction = GS1DigitalLinkToolkit.myfunction

2) Import the class, make an instance and call the method on it

class GS1DigitalLinkToolkit {
    function myfunction(){
        console.log('Function called');
    }
}
module.exports.gsclass = GS1DigitalLinkToolkit;

and

var gs = require('./gs1');
if (uncompressedDigitalLinkInput != "") {
    try {
        this.error3="";
        console.log("Test");
        gs1 = new gs.gsclass();
        gs1.myfunction();
    } 
    catch(err) {
        this.error3=err+"\n"+err.stack;
        return "";
    }
} 
else {
    return "";
}

For your main file test.js :

var gs = require('./gs1')
gs.myfunction();

And this required file gs1.js :

function myfunction() {
  console.log('Function called');
}

module.exports.myfunction = myfunction;

You should get:

$ node ./test.js
Function called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM