10 tricks to get your node. js app to run faster

Source: Internet
Author: User

node. JS benefits from its event-driven and asynchronous features, which are already fast. However, in the modern network is only fast is not good. If you're going to use node. js to develop your next Web app, then you should fair bet and make your app faster and surprisingly fast. This article will introduce 10, after testing that can greatly improve Node application skills. Don't say much nonsense, let's take a look.

1. Parallel

When creating a Web app, you may want to call the internal API multiple times to get a variety of data. For example, suppose you want to perform these calls on the Dashboard page:

  • User Information-getuserprofile ().

  • Current Activity-getrecentactivity ().

  • Subscribe to Content-getsubscriptions ().

  • Notification content-getnotifications ().

To get this information, you should create separate middleware for each method, and then link them to the Dashboard route. The problem, however, is that the execution of these methods is linear, and the next one does not start until the previous is finished. A viable solution is to call them in parallel.

As you know, because of asynchrony, node. JS is good at calling multiple methods in parallel. We can't throwaway. The methods I mentioned above have no dependencies, so we can execute them in parallel. This way we can reduce the number of middleware and greatly increase the speed.

We can use Async.js to handle parallelism, which is a Node module dedicated to JavaScript async. The following code shows how to invoke multiple methods in parallel with Async.js:

?
12345678910 functionrunInParallel() {  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 go to its GitHub page.

2. Asynchronous

According to 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 synchronous versions. The following code demonstrates both synchronous and asynchronous file read operations:

?
1234567 // Asynchronousfs.readFile(‘file.txt‘function(err, buffer) {  varcontent = buffer.toString();}); // Synchronousvarcontent = fs.readFileSync(‘file.txt‘).toString();

But if you do that long blocking operation, the main thread will be blocked until these operations are complete. This greatly reduces the performance of your application. Therefore, it is best to make sure that your code is using asynchronous version APIs, at least you should be asynchronous in the performance node. Also, you should be careful when choosing a third-party module. Because when you try to remove the sync from your code, a synchronous call from an external library can undo your performance.

3. Caching

If you use some infrequently changing data, you should cache them and improve performance. For example, the following code is an example of getting the latest post and showing it:

?
1234567891011 varrouter = express.Router();router.route(‘/latestPosts‘).get(function(req, res) {  Post.getLatest(function(err, posts) {    if(err) {      throwerr;    }    res.render(‘posts‘, { posts: posts });  });});

If you don't post more often, you can cache the list of posts and then clean them up after a while. For example, we can use the Redis module to achieve this goal. Of course, you must have Redis on your server. You can then use a client called Node_redis to save the key/value pair. The following example shows how we can cache posts:

?
1234567891011121314151617181920 varredis = require(‘redis‘),    client = redis.createClient(nullnull, { detect_buffers: true}),    router = express.Router();router.route(‘/latestPosts‘).get(function(req,res){  client.get(‘posts‘function(err, posts) {    if(posts) {      returnres.render(‘posts‘, { posts: JSON.parse(posts) });    }    Post.getLatest(function(err, posts) {      if(err) {        throwerr;      }      client.set(‘posts‘, JSON.stringify(posts));          res.render(‘posts‘, { posts: posts });    });  });});

See, let's check the Redis cache first to see if there are any posts. If so, let's take a list of these posts from the cache. Otherwise we will retrieve the database contents and then cache the results. Also, after a certain amount of time, we can clean up the Redis cache so that we can update the content.

4. gzip  compression

Turning on gzip compression can have a huge impact on your Web app. When a  gzip compression browser requests Some resources, the server compresses the response before it is returned to the browser. If you do not compress your static resources without gzip, it may take longer for the browser to get them.

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

?
1234 var  compression = require ( ' compression '  app.use (compression ());   //use  compression  app.use (Express. static Code class= "JScript Plain"));
5. If available, render with client

There are now powerful client MVC/MVVM frameworks, such as AngularJS, Ember, Meteor, and so on, to build a single page application becomes very simple. Basically, you just expose an API and return a JSON response to the client, without having to render the page on the server. On the client side, you can use the framework to organize the JSON and then display them on the UI. The server only sends JSON responses to save bandwidth and improve performance because you don't have to return layout tags in every response, right, you just need to return pure JSON and render them on the client.

Take a look at my tutorial, which is about how to expose a RESTful APIs with Express 4. I also wrote another tutorial that demonstrates how to combine these APIs with AngularJS.

6. Do not store too much data in Sessions

A typical Express page application, Session data is saved in memory by default. When you save too much data in the Session, it can lead to a significant increase in server overhead. So, either you switch to another storage mode to save the session data, or minimize the amount of data stored in the session.

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

7. Optimizing Queries

Suppose you have a blog and you want to show the latest posts on the home page. You may be able to fetch data by Mongoose:

?
123 Post.find().limit(10).exec(function(err, posts) {  //send posts to client});

The problem is that Mongoose's find () method queries all fields of the object, and many fields are not required on the home page. For example, Commentsis saves a reply to a particular post. We don't need to show the article reply, so we can get rid of it when we query. This will undoubtedly increase the speed. The above query can be optimized like this:

?
123 post.find (). Limit (. Exclude ( ' comments ' function ( err, posts)  {    / /send posts to client
8. Using the standard V8 method

Some operations on the collection, such as Map,reduce, and forEach do not necessarily support all browsers. Some browser compatibility issues can be resolved through the foreground library. But for node. js, you know exactly what Google's V8 JavaScript engine supports. This allows you to manipulate the collection directly on the server using these built-in methods.

9. Use Nginx in front of Node

Nginx is a small, 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 compress the response with Gzip on the Nginx, making all the responses smaller. So, if you have a product in operation, I think you should want to use Nginx to improve the speed of operation.

10. Packaging JavaScript

Finally, you can greatly improve the speed of the page application by packaging multiple JS files. When the browser touches the <script> element in the page render, it will be blocked until it gets the script to continue running (unless the async attribute is set). For example, if your page has five JavaScript files, the browser will issue five separate HTTP requests to get them. If you package these five files into one, the overall performance will be greatly improved. CSS files are the same. You can use a compilation tool such as GRUNT/GULP to package your resource files.

Conclusion

The top 10 tips will certainly improve the speed of your Web app. However, I know there is room for improvement and optimization. If you have any skills to improve your performance, let me know in your reply.

Thank you for reading!

10 tricks to get your node. js app to run faster

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.