I'm using node.js w/ express.js, and have following lines inside ./route/users.js:
exports.add = function(req, res) {
// some code here
this.list();
}
exports.delete = function(req, res) {
// some code here
this.list();
}
exports.list = function(req, res) {
// some code here
}
Problem is that this.list() doesn't work, what I get is this error: TypeError: Object # has no method 'list'
I've tried different approach too:
module.exports = {
add: function(req, res) {
// some code here
this.list();
},
delete: function(req, res) {
// some code here
this.list();
},
list: function(req, res) {
// some code here
this.list();
}
}
But didn't worked too.. Btw, if we ignore that error with list() calls, which one is correct way of writing routes?
One options is to define and refer to list as a local, then export it. Also note that you'll probably want to pass req and res when calling list().
function list(req, res) {
// ...
}
module.exports = {
add: function add(req, res) {
// ...
list(req, res);
},
delete: function (req, res) {
// ...
list(req, res);
},
list: list
};
The problem with using this is it's not tied to the exports object. The value of this within any given function depends on how that function was called rather than how it was defined.