Like any kind of apps, there are difficult issues to solve when we write Node apps.
In this article, we’ll look at some solutions to common problems when writing Node apps.
Create a Simple HTTP Proxy in Node.js
To create a simple HTTP proxy with Node.js, we can use the node-http-proxy
library.
We can install it by running:
npm install http-proxy --save
Then we can write:
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
http.createServer((req, res) => {
proxy.web(req, res, { target: 'http://www.example.com' });
}).listen(3000);
We call createProxyServer
to create the proxy server.
Then we call proxy.web
to redirect our request to http://example.com
.
fs.createReadStream vs fs.readFile in Node.js
We should use fs.createReadStream
to read a file one chunk at a time.
This means that we can read big files without loading all of the content into memory.
fs.readFile
is good for reading the entire file. This means it’s good for reading small files.
Read stream can accept data in a way that doesn’t overwhelm the host system.
Get the Domain Originating the Request in Express.js
We can get the domain of the originating request with Express.
All we have to do is to use req.get('host')
to get the HOST
header.
This works for a non-cross-origin request.
For a cross-origin request, we can use req.get('origin')
instead.
Also, we can use req.headers.host
and req.headers.origin
to do the same thing.
If we want to get a client’s IP address, we can use req.socket.remoteAddress
.
Create Mongoose Schema with an Array of Object IDs
To create a Mongoose schema with an array of object IDs, we can just pass in a constructor or schema to an array.
For instance, we can write:
const userSchema = mongoose.Schema({
lists: [listSchema],
friends: [{ type : ObjectId, ref: 'User' }]
});
exports.User = mongoose.model('User', userSchema);
We pass in listSchema
to use an existing schema for a schema with an array.
listSchema
is an existing Mongoose schema.
We can also pass in an object as we did with friends
.
We make friends
reference itself.
Listen to All Emitted Events in Node.js
To listen to all emitted events, we can use a wildcard to do it.
We can do that with the eventemitter2
package.
It supports namespacing and wildcards.
For instance, we can write:
const EventEmitter2 = require('eventemitter2');
const emitter = new EventEmitter2({
wildcard: false,
delimiter: '.',
newListener: false,
removeListener: false,
maxListeners: 10,
verboseMemoryLeak: false,
ignoreErrors: false
});
emitter.on('bar.*', (val) => {
console.log(this.event, valu);
});
We listen to all events with names starting with bar.
Also, we can listen to multiple events and events with identifiers denoted with symbols.
Accessing Express.js Local Variables in Client-Side JavaScript
We can access Express local variables in client-side JavaScript.
All we have to do is to pass in an object as the 2nd argument of res.render
.
Then we can access the variable by the key names.
For instance, we can write:
res.render('index', {
title: 'page title',
urls: JSON.stringify(urls),
});
Then we can access them by writing:
const urls = !{urls};
in our Jad template
We’ve to stringify urls
since the variables are added with string interpolation.
How to Check if Headers have Already Sent with Express
We can check if headers are already sent with the res.headerSent
property.
For instance, we can write:
if (res.headersSent) {
//...
}
Convert Timestamp to Human Date
We can convert a timestamp to a human date by using the Date
constructor.
For example, we can write:
const date = new Date(1591399037536);
Then we can call toDateString
, toTimeString
, or toLocaleDateString
to format the string the way we like.
Measuring Timing of Code in a Node App
To measure the timing of Node apps, we can use the performance.now()
method to do that.
For example, we can write:
const {
performance
} = require('perf_hooks');
console.log(performance.now());
We just import the performance
object from perf_hooks
and then call the now
method on it.
Conclusion
We can use the performance.now()
method to measure performance.
To create an HTTP proxy, we can use a 3rd party package to do it.
Mongoose schemas can have arrays in it.
We can get the request’s hostname from the headers in Express.
Read streams are good for reading big files, readFile
is good for reading small files.