10 tips for optimizing the speed of node. js Web applications

  • 2020-03-30 03:49:40
  • OfStack

Node.js has benefited from its event-driven and asynchronous nature, and is already fast. However, in the modern network just fast is not good. If you're going to build your next Web application with node. js, you should do everything you can to make your application faster, faster than ever. This article introduces 10 techniques that have been proven to significantly improve Node applications. Without further ado, let's look at each item.

1. The parallel

When you create a Web application, you may have to call the internal API several times to get all kinds of data. For example, suppose you're on a Dashboard page and you want to make the following calls:

User information -getUserProfile().

Current activity -getRecentActivity().

Subscription content -getSubscriptions().

Notification content -getNotifications().

To get this information, you should create separate middleware for each method and link them to the Dashboard route. The problem is, the execution of these methods is linear, and the next one doesn't start until the last one ends. The possible solution is to invoke them in parallel.

As you know, node. js is very good at calling multiple methods in parallel because of its asynchronous nature. We can't waste anything. The methods I mentioned above have no dependencies, so we can execute them in parallel. In this way, we can reduce the number of middleware and improve the speed greatly.

We can handle parallelism with async.js, a Node module specifically designed to teach JavaScript asynchrony. The following code demonstrates how to call multiple methods in parallel using async.js:


function runInParallel() {
  async.parallel([
    getUserProfile,
    getRecentActivity,
    getSubscriptions,
    getNotifications
  ], function(err, results) {
    //This callback runs when all the functions complete
  });
}

If you want to more in-depth understanding of async. Js, please click the page (link: https://github.com/caolan/async).

2. The asynchronous

By design, node. js is single-threaded. At this point, synchronous code can clog up the entire application. For example, most file system apis have synchronous versions of them. The following code demonstrates both synchronous and asynchronous operations for 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 do that kind of blocking for a long time, the main thread will be blocked until those operations are complete. This significantly reduces the performance of your application. So, it's best to make sure that you're using the asynchronous version of the API in your code, 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 get synchronization out of your code, a synchronous call from an external library can throw everything away and degrade your application's performance.

3. The cache

If you use data that doesn't change very often, you should cache it to improve performance. For example, the following code is an example of getting the latest post and displaying it:


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 your list of posts and clean them up later. For example, we can use the Redis module to achieve this. Of course, you must install Redis on your server. Then you can save the key/value pairs with a client called node_redis. 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, let's first check the Redis cache to see if there are posts. If so, we take the list of posts from the cache. Otherwise we retrieve the database contents and cache the results. In addition, after a certain amount of time, we can clean up the Redis cache so that the content can be updated.

4. The gzip compression

Turning on gzip has a huge impact on your Web applications. When a gzip browser requests certain resources, the server compresses the response before it is returned to the browser. If you don't use gzip to compress your static resources, the browser may take longer to get them.

In the Express application, we can use the built-in express.static() middleware to handle static content. In addition, static content can be compressed and processed using compression middleware. Here is the use case:


var compression = require('compression'); app.use(compression()); //use compression
app.use(express.static(path.join(__dirname, 'public')));

Render on the client side if possible

With powerful client MVC/MVVM frameworks such as AngularJS,Ember,Meteor, etc., building a single page application is easy. Basically, you just expose an API and return a JSON response to the client without rendering the page on the server. On the client side, you can use a framework to organize JSON and then display it on the UI. Sending only JSON responses from the server saves bandwidth and improves performance because you don't need to return layout tags in every response, right? You just need to return pure JSON and render them on the client side.

Take a look at my tutorial on how to expose a RESTful API with Express 4. I also wrote another tutorial showing 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 store too much data in sessions, the server overhead increases significantly. So, either you switch to another storage method to save Session data, or you try to reduce the amount of data stored in Session.

For example, when a user logs into your application, you can save their ID only in Session instead of the entire user data object. Also, for queries where you can get an object from an id, you might like to use MongoDB or Redis to store session data.

7. Optimize queries

Suppose you have a blog and you want to display the latest posts on the home page. You might use Mongoose to fetch data like this:


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

The problem is that Mongoose's find() method looks up all the fields of the object, and many fields are not required on the home page. Commentsis, for example, saves replies to specific posts. We don't need to display an article reply, so we can remove it from the query. This will undoubtedly increase the 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 the standard V8 approach

9. Use Nginx in front of Node

Nginx is a small, lightweight Web server that you can use to 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 nginx to make all the responses smaller. So, if you have a product in operation, I think you might want to use nginx to improve speed.

10. Packaging JavaScript

Finally, you can greatly improve the speed of page application by packaging multiple JS files. When the browser hits in the page render Script> The element is blocked until the script is available (unless the asynchronous attribute is set). For example, if your page has five JavaScript files, the browser makes five separate HTTP requests to get them. If these five files are compressed into one, the overall performance can be greatly improved. The same goes for CSS files. You can package your resource files with a compiler such as Grunt/Gulp.

conclusion

The above 10 tips are sure to speed up your Web application. However, I know there is room for improvement and optimization. If you have any tips for improving performance, let me know in the comments.

Thanks for reading!


Related articles: