10 tips to make your Node. js application run faster

Source: Internet
Author: User

10 tips to make your Node. js application run faster

Node. js has quickly benefited from its event-driven and asynchronous features. 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:

 
 
  1. function runInParallel() {  
  2.   async.parallel([  
  3.     getUserProfile,  
  4.     getRecentActivity,  
  5.     getSubscriptions,  
  6.     getNotifications  
  7.   ], function(err, results) {  
  8.     //This callback runs when all the functions complete  
  9.   });  

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:

 
 
  1. // Asynchronous  
  2. fs.readFile('file.txt', function(err, buffer) {  
  3.   var content = buffer.toString();  
  4. });  
  5.    
  6. // Synchronous  
  7. 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:

 
 
  1. var router = express.Router();  
  2.    
  3. router.route('/latestPosts').get(function(req, res) {  
  4.   Post.getLatest(function(err, posts) {  
  5.     if (err) {  
  6.       throw err;  
  7.     }  
  8.    
  9.     res.render('posts', { posts: posts });  
  10.   });  
  11. }); 

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:

 
 
  1. var redis = require('redis'),  
  2.     client = redis.createClient(null, null, { detect_buffers: true }),  
  3.     router = express.Router();  
  4.    
  5. router.route('/latestPosts').get(function(req,res){  
  6.   client.get('posts', function (err, posts) {  
  7.     if (posts) {  
  8.       return res.render('posts', { posts: JSON.parse(posts) });  
  9.     }  
  10.    
  11.     Post.getLatest(function(err, posts) {  
  12.       if (err) {  
  13.         throw err;  
  14.       }  
  15.    
  16.       client.set('posts', JSON.stringify(posts));      
  17.       res.render('posts', { posts: posts });  
  18.     });  
  19.   });  
  20. }); 

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:

 
 
  1. var compression = require('compression');  
  2.    
  3. app.use(compression()); //use compression   
  4. 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:

 
 
  1. Post.find().limit(10).exec(function(err, posts) {  
  2.   //send posts to client  
  3. }); 

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:

 
 
  1. Post.find().limit(10).exclude('comments').exec(function(err, posts) {  
  2.   //send posts to client  
  3. }); 

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 is 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!

10 Tips to Make Your Node. js Web App Faster

By http://www.oschina.net/translate/10-tips-make-node-js-web-app-faster

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.