10 Tips for optimizing Node.js Web application running Speed _node.js

Source: Internet
Author: User
Tags redis install redis

Node.js benefits from its event-driven and asynchronous features, which are already fast. But in modern networks, it's just not going to work. If you're going to use node.js to develop your next Web application, you should do anything you can to make your application faster and abnormally fast. In this article, we will introduce 10 techniques that can greatly improve Node application by testing. Don't say much nonsense, let's take a look at it.

1. Parallel

When creating a WEB application, you may want to call the internal APIs multiple times to get a variety of data. For example, suppose on the Dashboard page you want to perform the following calls:

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 begin until the previous end. A viable solution is to call them in parallel.

As you know, because of Asynchrony, Node.js is very good at calling multiple methods in parallel. We can't waste. The methods I mentioned above are not dependent, so we can execute them in parallel. This allows us to reduce the number of middleware and dramatically increase the speed.

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

Copy Code code as follows:

function Runinparallel () {
Async.Parallel ([
GetUserProfile,
Getrecentactivity,
GetSubscriptions,
GetNotifications
], function (err, results) {
This callback runs the functions complete
});
}

If you want to get a deeper understanding of async.js, please go to its GitHub page.

2. Asynchronous

According to the design Node.js is single thread. Based on this, synchronization code blocks the entire application. For example, most file system APIs have their synchronized versions. The following code demonstrates both synchronous and asynchronous operation of file reads:

Copy Code code 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 that long blocking operation, the main thread will be blocked until these operations are complete. This greatly reduces the performance of your application. So, it's best to make sure that your code uses asynchronous version APIs, at least you should be asynchronous at the performance node. Also, you should be careful when choosing a third party module. Because when you try to remove sync from your code, a synchronization call from an external library will undo your application and reduce your performance.

3. Caching

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

Copy Code code 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 regularly, you can cache the list of posts and then clean them out after a while. For example, we can use the Redis module to achieve this goal. Of course, you have to install Redis on your server. You can then use a client called Node_redis to save the key/value pairs. The following example shows how we cache posts:
Copy Code code 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 are any posts. If so, we take a list of these posts from the cache. Otherwise, we retrieve the contents of the database and then cache the results. In addition, after a certain amount of time, we can clean the Redis cache so that we can update the content.

4. Gzip compression

Opening gzip compression can have a huge impact on your WEB application. When a gzip compression browser requests Some resources, the server compresses the response before it is returned to the browser. If you don't need to use gzip to compress your static resources, it may take a long time for browsers to get them.

In Express applications, we can use the built-in express.static () middleware to handle static content. In addition, static content can be compressed and processed with compression middleware. Here's how to use the example:

Copy Code code as follows:

var compression = require (' compression ');

App.use (compression ()); Use compression
App.use (Express.static (Path.join (__dirname, ' public '));

5. If possible, render with client

Now there are super powerful client MVC/MVVM frameworks, such as Angularjs,ember,meteor, and so on, building a single page application becomes very simple. Basically, you just expose an API and return JSON response to the client, without the need to render the page on the server side. On the client side, you can use frames to organize JSON and then display them on the UI. Server-side sending only JSON responses can save bandwidth and improve performance because you don't need to return layout tags in every response, you just need to return pure JSON and then render them on the client.

Take a look at my tutorial, it's about how to use Express 4 to expose a RESTful APIs. I also wrote another tutorial demonstrating how to combine these APIs with Angularjs.

6. Do not store too much data in Sessions

A typical Express page application, the session data is stored in memory by default. When you save too much data in session, the server overhead is significantly increased. So either you switch to another storage mode to save the session data, or you minimize the amount of data stored in the session.

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

7. Optimize the query

Let's say you have a blog and you want to display the latest posts on the home page. You might get data like this by mongoose:

Copy Code code as follows:

Post.find (). Limit (a). EXEC (function (err, posts) {
Send posts to Client
});

The problem, however, is that the mongoose 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 specific post. We don't need to display the article reply, so we can get rid of it in the query. This will undoubtedly improve speed. You can optimize the above query like this:
Copy Code code as follows:

Post.find (). Limit. Exclude (' comments '). EXEC (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. We can solve some of the browser compatibility issues through the library at the front desk. But for node.js, you need to know exactly what Google's V8 JavaScript engine supports. In this way, you can use these built-in methods to manipulate the collection directly on the server side.

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 the static resources on the Nginx rather than on Node. You can compress the response with Gzip on the nginx to make 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 the operation.

10. Pack JavaScript

Finally, you can greatly improve the application speed of the page, by packaging multiple JS files. When the browser encounters <script> elements in page rendering, it is blocked until the script is received to continue (unless an asynchronous property is set). For example, if your page has five JavaScript files, the browser will issue five separate HTTP requests to get them. If you compress these five files into one, the overall performance will be significantly improved. The same is true for CSS files. You can use a compilation tool such as GRUNT/GULP to package your resource files.

Conclusion

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

Thanks for reading!

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.