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?
To call another function in the same helper, use the syntax: this. methodName , where this is a reference to the helper itself.
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.
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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With