How do you call a function from within another function in a module.exports
declaration?
var bla = require(\'./bla.js\');
console.log(bl
You can also do this to make it more concise and readable. This is what I've seen done in several of the well written open sourced modules:
var self = module.exports = {
foo: function (req, res, next) {
return ('foo');
},
bar: function(req, res, next) {
self.foo();
}
}
Another option, and closer to the original style of the OP, is to put the object you want to export into a variable and reference that variable to make calls to other methods in the object. You can then export that variable and you're good to go.
var self = {
foo: function (req, res, next) {
return ('foo');
},
bar: function (req, res, next) {
return self.foo();
}
};
module.exports = self;
You could declare your functions outside of the module.exports
block.
var foo = function (req, res, next) {
return ('foo');
}
var bar = function (req, res, next) {
return foo();
}
Then:
module.exports = {
foo: foo,
bar: bar
}
Change this.foo()
to module.exports.foo()
Starting with Node.js version 13 you can take advantage of ES6 Modules.
export function foo() {
return 'foo';
}
export function bar() {
return foo();
}
Following the Class approach:
class MyClass {
foo() {
return 'foo';
}
bar() {
return this.foo();
}
}
module.exports = new MyClass();
This will instantiate the class only once, due to Node's module caching:
https://nodejs.org/api/modules.html#modules_caching
You can also save a reference to module's global scope outside the (module.)exports.somemodule definition:
var _this = this;
exports.somefunction = function() {
console.log('hello');
}
exports.someotherfunction = function() {
_this.somefunction();
}