Home  >  Article  >  Web Front-end  >  10 tips for optimizing the speed of your Node.js web application_node.js

10 tips for optimizing the speed of your Node.js web application_node.js

WBOY
WBOYOriginal
2016-05-16 16:37:421005browse

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

// 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:

Copy code The code is as follows:

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:
Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:
Copy code The code is as follows:

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