I'm attempting to write a node module in order to clean up my code and separate it out into different files.
Consider the below code:
module.exports = {
Hello : function(request, reply) {
return reply("Hello " + World());
},
World : function() {
return "World";
}
}
If I import the above module and use the Hello function as handler for a specific route, i get an HTTP 500 internal server error.
I've narrowed the problem down to the call to World(), if I change the Hello function to
Hello : function(request, reply) {
return reply("Hello World");
}
Then it works fine, so it seems that it is being tripped up when calling another function from within the export object
Does anyone know why this is happening and how to resolve it?
To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.
var module = require('module_name'); As per above syntax, specify the module name in the require() function. The require() function will return an object, function, property or any other JavaScript type, depending on what the specified module returns. The following example demonstrates how to use Node.
You should call it as follows:
module.exports = {
Hello: function(request, reply) {
return reply("Hello " + module.exports.World());
},
World: function() {
return "World";
}
}
If you are aiming for cleaner code, I suggest that you change the code to this:
function World() {
return "World";
}
function Hello(request, reply) {
return reply("Hello " + World());
}
module.exports = {
Hello,
}
This will make your code more readable and you will only be exporting what you actually need. This question has other solutions to your issue.
Well let's demonstrate the this
this
doesn't define the object that the function resides in. It defines from where the function is called. So while;
var obj = {
Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
};
obj.Hello("test", console.log);
would work just fine; This wouldn't;
var obj = { Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
};
setTimeout(obj.Hello,100,"test",console.log);
This is just because the obj.Hello
will be assigned an argument in setTimeOut
function's definition and that argument will be invoked as window
being the this
for that function. So you should instead do like;
var obj = { Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
};
setTimeout(obj.Hello.bind(obj),100,"test",console.log);
//or
setTimeout(obj.Hello.bind(obj,"test",console.log),100);
//or
setTimeout((x,y) => obj.Hello(x,y),100,"test",console.log);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With