Node.js is already fast thanks to its event-driven and asynchronous nature. However, just being fast is not enough in modern networks. If you're going to use Node.js to develop your next web application, then you should do whatever it takes to make your application faster, blazingly fast. This article will introduce 10 tested tips that can greatly improve Node applications. Without further ado, let’s look at them one by one.
1. Parallel
When creating a web application, you may have to call the internal API multiple times to obtain various data. For example, suppose that on the Dashboard page, you want to execute the following calls:
User information -getUserProfile().
Current activity -getRecentActivity().
Subscription content -getSubscriptions().
Notification content -getNotifications().
To get this information, you would create separate middleware for each method and then link them to the Dashboard route. But the problem is that the execution of these methods is linear, and the next one will not start until the previous one ends. A possible solution is to call them in parallel.
As you know Node.js is very good at calling multiple methods in parallel due to asynchronicity. We cannot waste our resources. Those methods I mentioned above have no dependencies so we can execute them in parallel. In this way we can reduce the amount of middleware and greatly increase the speed.
We can use async.js to handle parallelism, which is a Node module specially used to tune JavaScript asynchronously. The following code demonstrates how to use async.js to call multiple methods in parallel:
2. Asynchronous
Node.js is single-threaded by design. Based on this, synchronous code can clog the entire application. For example, most file system APIs have their synchronous versions. The following code demonstrates both synchronous and asynchronous operations of file reading:
// Synchronous
var content = fs.readFileSync('file.txt').toString();
3. Caching
If you use some data that does not change frequently, you should cache it to improve performance. For example, the following code is an example of getting the latest posts and displaying them:
router.route('/latestPosts').get(function(req, res) {
Post.getLatest(function(err, posts) {
If (err) {
throw err;
}
res.render('posts', { posts: posts });
});
});
router.route('/latestPosts').get(function(req,res){
client.get('posts', function (err, posts) {
If (posts) {
Return res.render('posts', { posts: JSON.parse(posts) });
}
Post.getLatest(function(err, posts) {
If (err) {
throw err;
}
client.set('posts', JSON.stringify(posts));
res.render('posts', { posts: posts });
});
});
});
4. gzip compression
Enabling gzip compression can have a huge impact on your web application. When a gzip-compressed browser requests some resource, the server compresses the response before returning it to the browser. If you don't gzip your static resources, it may take longer for the browser to get them.
In Express applications, we can use the built-in express.static() middleware to handle static content. Additionally, static content can be compressed and processed using compression middleware. The following is a usage example:
app.use(compression()); //use compression
app.use(express.static(path.join(__dirname, 'public')));
5. If possible, use client-side rendering
Nowadays, there are many versatile and powerful client-side MVC/MVVM frameworks, such as AngularJS, Ember, Meteor, etc., making it very easy to build a single-page application. Basically, you just expose an API and return a JSON response to the client without rendering the page on the server side. On the client side, you can use frames to organize JSON and display them on the UI. Sending only JSON responses on the server saves bandwidth and improves performance because you don't need to return layout markup in every response, right? You just need to return pure JSON and then render them on the client.
Check out this tutorial of mine on how to expose a RESTful APIs with Express 4. I also wrote another tutorial that demonstrates how to combine these APIs with AngularJS.
6. Don’t store too much data in Sessions
In a typical Express page application, Session data is stored in memory by default. When you save too much data in Session, server overhead will increase significantly. So, either you switch to another storage method to save Session data, or try to reduce the amount of data stored in Session.
For example, when a user logs into your application, you can save only their ID in the Session instead of the entire user data object. Also, for queries where you can get the object by id, you might like to use MongoDB or Redis to store the session data.
7. Optimize query
Suppose you have a blog and you want to display the latest posts on the homepage. You may retrieve data through Mongoose like this:
8. Use standard V8 method
Some operations on collections, such as map, reduce, and forEach, may not be supported in all browsers. We can solve some browser compatibility issues through the front-end library. But for Node.js, you need to know exactly what operations Google's V8 JavaScript engine supports. In this way, you can directly use these built-in methods to operate on the collection on the server side.
9. Use Nginx in front of Node
Nginx is a tiny, lightweight web server that can reduce the load on your Node.js server. You can configure static resources on nginx instead of Node. You can use gzip to compress responses on nginx, making all responses smaller. So, if you have a product that is running, I think you will want to use nginx to improve the running speed.
10. Packaging JavaScript
Finally, you can also greatly improve page application speed by packaging multiple JS files. When the browser encounters the