10 tips for optimizing the running speed of Node. jsWeb applications _ node. js

Source: Internet
Author: User
This article mainly introduces how to optimize Node. this article describes the ten tips for jsWeb application running speed, including parallel, asynchronous, cache, gzip compression, and client rendering. If you need them, refer to Node. js has benefited from its event-driven and asynchronous features, and has become very fast. However, in modern networks, it is only fast. If you plan to use Node. js to develop your next Web application, you should have no need for it, so that your application can be faster and exception faster. This article will introduce 10 articles. It has been tested that it can greatly improve the skills of Node applications. Let's take a look at it one by one.

1. Parallel

When creating a Web application, you may need to call internal APIs multiple times to obtain various data. For example, on the Dashboard page, you need to execute the following calls:

User information-getUserProfile ().

Current Activity-getRecentActivity ().

Subscription content-getSubscriptions ().

Notification content-getNotifications ().

To obtain this information, you should create independent middleware for each method and link them to the Dashboard route. However, the problem is that the execution of these methods is linear, And the next method will not start before the last one ends. A feasible solution is to call them in parallel.

As you know, Node. js is very good at calling multiple methods in parallel due to Asynchronization. We cannot attack things. The methods I mentioned above do not have dependencies, so we can execute them in parallel. In this way, we can reduce the number of middleware and greatly increase the speed.

We can use async. js to process parallelism. It is a Node module specially designed to call JavaScript Asynchronization. The following code demonstrates how to use async. js to call multiple methods in parallel:

The Code is as follows:


Function runInParallel (){
Async. parallel ([
GetUserProfile,
GetRecentActivity,
GetSubscriptions,
Getconfigurications
], Function (err, results ){
// This callback runs when all the functions complete
});
}


If you want to learn more about async. js, go to its GitHub page.

2. asynchronous

According to the design, Node. js is single-threaded. Based on this, the synchronization code will block the entire application. For example, most file system APIs have their synchronization versions. The following code demonstrates two operations: synchronous and asynchronous:

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 ();


However, if you perform a long blocking operation, the main thread will be blocked until these operations are completed. This greatly reduces the performance of your application. Therefore, it is best to make sure that your code uses an asynchronous version of the API, at least you should be asynchronous in the performance node. Also, be careful when choosing a third-party module. Because when you try to remove the synchronization operation from your code, the synchronous calling of an external library will make you useless and reduce your application performance.

3. Cache

If you use infrequently changed data, You Should cache it to improve performance. For example, the following code gets the latest post and shows an example:

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 do not post a post frequently, You Can cache the post list and clear it after a while. For example, we can use the Redis module to achieve this goal. Of course, you must install Redis on your server. Then you can use a client called node_redis to save the key/value pair. The following example shows how to cache a post:

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 });
});
});
});


Check the Redis cache to see if there are any posts. If yes, we will take the list of these posts from the cache. Otherwise, we will retrieve the database content and cache the results. In addition, after a certain period of time, we can clear the Redis cache so that we can update the content.

4. gzip Compression

Enabling gzip compression has a huge impact on your Web applications. When a gzip compression browser requests certain resources, the server compresses the data before the response is returned to the browser. If you do not need gzip to compress your static resources, it may take longer for the browser to obtain them.

In Express applications, we can use the built-in express. static () middleware to process static content. In addition, you can use compression middleware to compress and process static content. The following is an example:

The Code is as follows:


Var compression = require ('compression ');

App. use (compression (); // use compression
App. use (express. static (path. join (_ dirname, 'public ')));

5. If you can, use the client to render

Now there are powerful client MVC/MVVM frameworks, such as AngularJS, Ember, Meteor, and so on. It is very easy to build a single page application. Basically, you only need to publish an API and return a JSON response to the client, instead of rendering the page on the server. On the client, you can use the Framework to organize JSON and display them on the UI. The server can only send a JSON response to save bandwidth and improve performance, because you do not need to return the layout mark in each response, right? You only need to return the pure JSON, then render them on the client.

Let's take a look at my tutorial on how to use Express 4 to publish a RESTful APIs. I also wrote another tutorial to demonstrate how to combine these APIs with AngularJS.

6. Do not store too much data in Sessions

For typical Express page applications, Session data is stored in memory by default. When you store too much data in the Session, the server overhead will increase significantly. Therefore, either you switch to another storage method to save Session data or minimize the amount of data stored in the Session.

For example, when a user logs on to your application, you can only save their ID in the Session instead of the entire user data object. Also, for queries that you can get objects from IDs, you should like to use MongoDB or Redis to store session data.

7. Optimize Query

Suppose you have a blog and you want to display the latest post on the home page. You may use Mongoose to retrieve data like this:

The Code is as follows:


Post.find().limit(102.16.exe c (function (err, posts ){
// Send posts to client
});


However, the problem is that the Mongoose find () method will query all the fields of the object, and many fields are not required on the home page. For example, commentsis stores the reply of a specific post. We do not need to display the article reply, so we can remove it during the query. This will undoubtedly increase the speed. You can optimize the above query as follows:

The Code is as follows:


Post.find().limit(10).exclude('comments'cmd.exe c (function (err, posts ){
// Send posts to client
});

8. Use the standard V8 Method

Some operations on the set, such as map, reduce, and forEach, do not necessarily support 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 on the server to operate the set.

9. Use Nginx before Node

Nginx is a small and 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 the response on nginx to make all the responses smaller. Therefore, if you have a product in operation, I think you should want to use nginx to improve the running speed.

10. Pack JavaScript

Finally, you can greatly increase the page application speed by packaging multiple JS files. When the browser encounters the script element in page rendering, it will be blocked until the script is obtained (unless an asynchronous attribute is set ). For example, if your page has five JavaScript files, the browser will send five independent HTTP requests to get them. If you compress these five files into one, the overall performance will be greatly improved. The same is true for CSS files. You can use compilation tools such as Grunt/Gulp to package your resource files.

Conclusion

The above 10 tips can certainly increase the speed of your Web application. However, I know there is still room for improvement and optimization. If you have any skills to improve performance, tell me in the reply.

Thank you for reading!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.