Is it Ok to make the exports object a function in CommonJS?
Problem
In the case the a CommonJS module only need to return one function, is it good practice to assign it directly to the Exports object? (as opposed to assigning it as the only attribute of the exports object)
For example (imaginary log.js
module):
module.exports = function(text){console.log(text);}
usage:
var log = require('./log');
log('something');
Problem courtesy of: Ped
Solution
Yes. I often use this practice myself. It's also a good fit with the revealing module pattern, e.g.:
module.exports = function(db) {
return {
get: function(id, callback) {
// db.get(...)
},
save: function(obj, callback) {
// db.save(...)
}
}
};
It's also widely used in connect (e.g. csrf module) and express (e.g. route).
Solution courtesy of: Linus Gustav Larsson Thiel
Discussion
View additional discussion.