


10 tips for optimizing the speed of your Node.js web application_node.js
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:
function runInParallel() {
async.parallel([
GetUserProfile,
GetRecentActivity,
GetSubscriptions,
GetNotifications
], function(err, results) {
//This callback runs when all the functions complete
});
}
If you want to learn more about async.js, please visit its GitHub page.
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:
// Asynchronous
fs.readFile('file.txt', function(err, buffer) {
var content = buffer.toString();
});
// Synchronous
var content = fs.readFileSync('file.txt').toString();
But if you perform long-term blocking operations, the main thread will be blocked until these operations are completed. This greatly reduces the performance of your application. Therefore, it is best to ensure that your code is using the asynchronous version of the API. At the very least, you should be asynchronous on the performance node. Also, you should be careful when choosing third-party modules. Because when you try to eliminate synchronization operations from your code, a synchronous call from an external library will undo all your efforts and reduce your application performance.
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:
var router = express.Router();
router.route('/latestPosts').get(function(req, res) {
Post.getLatest(function(err, posts) {
If (err) {
throw err;
}
res.render('posts', { posts: posts });
});
});
If you don't post often, you can cache the list of posts and clear them after a period of time. For example, we can use the Redis module to achieve this purpose. Of course, you must have Redis installed on your server. You can then use a client called node_redis to save the key/value pairs. The following example demonstrates how we cache posts:
var redis = require('redis'),
Client = redis.createClient(null, null, { detect_buffers: true }),
Router = express.Router();
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 });
});
});
});
See, we first check the Redis cache to see if there is a post. If there are, we get the list of posts from the cache. Otherwise we retrieve the database contents and cache the results. Additionally, after a certain amount of time, we can clear the Redis cache so the content can be updated.
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:
var compression = require('compression');
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:
Post.find().limit(10).exec(function(err, posts) {
//send posts to client
});
But the problem is that Mongoose's find() method will query all fields of the object, and many fields are not required on the homepage. For example, commentsis stores replies to a specific post. We don't need to display article replies, so we can exclude them when querying. This will definitely increase speed. You can optimize the above query like this:
Post.find().limit(10).exclude('comments').exec(function(err, posts) {
//send posts to client
});
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

Detailed explanation of the tips for using the √ symbol in the Word box. In daily work and study, we often need to use Word for document editing and typesetting. Among them, the √ symbol is a common symbol, which usually means "right". Using the √ symbol in the Word box can help us present information more clearly and improve the professionalism and beauty of the document. Next, we will introduce in detail the skills of using the √ symbol in the Word box, hoping to help everyone. 1. Insert the √ symbol In Word, there are many ways to insert the √ symbol. one

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star
