Writing express.js app. Where do helper methods go?
It really depends of what your helper is doing. If it operates with data which is passed as a parameter to it then you may save it in an external module and use require
to access it.
// helpers/FormatString.jsmodule.exports = function(str) { return str.toUpperCase();}// app.jsvar formatter = require("./helpers/FormatString");
However, if you need to modify the request
or the response
object then I'll suggest to define it as a middleware. I.e.:
app.use(function(req, res, next) { // ... do your stuff here});
@Krasimir gave a correct answer. Regarding your question how to deal with asynchronous helper functions I can give you an example (not the usual foo/bar, but one of my own helper functions):
var cached; // as modules can act like singletons I can share values heremodule.exports = function fetchGoogleCerts(options, callback) { // <-- callback var now = Date.now(); if (ttl > now && cached) { callback(null, cached); // <-- return with success return; } request({ uri: options.certsUrl || defaultCertsUrl, strictSSL: true }, function (err, response, body) { var error, certs; if (!err && response.statusCode === 200) { certs = jsonParse(body); // a local function if (!certs) { callback('parse_error', null); // <-- return an error return; } cached = certs; // ... more code callback(null, cached); // <-- success case } else { error = { error: err, statusCode: response.statusCode }; log.error(error, 'error fetching google certs'); callback(error); // <-- return an error } }); }};
And using the helper:
fetchGoogleCerts = require('./google-certs.js'),module.exports = function fetchCertsAndDecodeIdToken(token, options, callback) { fetchGoogleCerts(options, function (err, googleCerts) { if (err) { callback({ errorCode: codes.io_error, errorMsg: 'Unable to fetch Google certificates', error: err }); return; } decodeAndVerifyGoogleIdToken(googleCerts, token, options, callback); });};
As you can see above, the simple solution is to provide a callback function to your asynchronous helper function.
Of course you can also export an Object which extends EventEmitter
, then you might not need a callback function, but register for the events. Here is an Example for a helper which emits events.