Reputation: 145
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?
Upvotes: 0
Views: 1218
Reputation: 123
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 "";
}
Upvotes: 1
Reputation: 14336
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
Upvotes: 0