Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing express.js app. Where do helper methods go?

So I have started with express.js - my first JS web dev framework. I didn't make anything small, but started a bigger project. I'm learning, and building at the same time.

Coming from a Python/Flask background, express seems very complicated.

Like in python, if I want a helper method, I can just put it on top of the file, or in a new module, and import it. Super easy. But in node/express, things are async, and everything is in exports or module.exports (??). Where do helper methods go? How do I call them with callbacks?

In another question I asked, I was doing the same kind of computation multiple times. In Python, I would write a method (with if statements and parameters), and call it multiple times, using a for.. in... loop. The code I have right now is very redundant.

How do I do it in express? What are best practices for writing express code?

like image 745
KGo Avatar asked Jan 04 '14 21:01

KGo


People also ask

How do you call a helper function in JavaScript?

To call another function in the same helper, use the syntax: this. methodName , where this is a reference to the helper itself.

What is helpers in node JS?

The node helper ( node_helper. js ) is a Node. js script that is able to do some backend task to support your module. For every module type, only one node helper instance will be created. For example: if your MagicMirror uses two calendar modules, there will be only one calendar node helper instantiated.

How do you load a middleware function?

To load the middleware function, call app. use() , specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/). Every time the app receives a request, it prints the message “LOGGED” to the terminal.

Which method is used to send the content in Express js?

send() Function. The res. send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array.


1 Answers

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.js
module.exports = function(str) {
   return str.toUpperCase();
}

// app.js
var 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
});
like image 82
Krasimir Avatar answered Sep 23 '22 11:09

Krasimir