Node.js has benefited from its event-driven and asynchronous features, and has been very soon. However, it is not possible to be fast in modern networks. If you plan to use Node.js to develop your next web application, then you should do everything to make your application faster and exceptionally fast. This article will introduce 10 items, and after testing, it can greatly improve the skills of Node application. Without further ado, let's take a look one by one.
1. Parallel
When creating a web application, you may have to call the internal API multiple times to obtain various data. For example, suppose on the Dashboard page, you have to execute 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. But the problem is that the execution of these methods is linear, and the next one will not start until the previous one is finished. 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 asynchronousness. We cannot waste natural resources. 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 greatly increase the speed.
We can use async.js to handle parallelism, which is a Node module specially used to train JavaScript asynchronously. The following code demonstrates how to use async.js to call multiple methods in parallel:
The code copy is as follows:
function runInParallel() {
async.parallel([
getUserProfile,
getRecentActivity,
getSubscriptions,
getNotifications
], function(err, results) {
//This callback runs when all the functions complete
});
}
If you want to have a more in-depth look at async.js, please move on its GitHub page.
2. Asynchronous
By design Node.js is single threaded. Based on this, synchronous code will block the entire application. For example, most file system APIs have their synchronized versions. The following code demonstrates two operations: Synchronous and asynchronous file reading:
The code copy 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 such long-term blocking operations, 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 the asynchronous version of the API, at least you should be asynchronous in the performance node. Moreover, you should be very careful when choosing third-party modules. Because when you try to remove synchronization operations from your code, a synchronous call from an external library will waste all your efforts and reduce your application performance.
3. Cache
If you use some data that does not 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:
The code copy 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 don't post frequently, you can cache the post list and clean them up 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. Then you can save key/value pairs with a client called node_redis. The following example shows how we cache posts:
The code copy 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 });
});
});
});
See, let's check the Redis cache first to see if there are any posts. If so, we take these post lists from the cache. Otherwise we will retrieve the database content and cache the results. In addition, after a certain period of time, we can clean the Redis cache so that the content can be updated.
4. gzip compression
Turning on gzip compression will have a huge impact on your web applications. When a gzip compressed browser requests certain resources, the server compresses before the response is returned to the browser. If you don't use gzip to compress your static resources, it may take longer for the browser 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 using the compression middleware. Here are the usage examples:
The code copy is 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 versatile and powerful client MVC/MVVM frameworks, such as AngularJS, Ember, Meteor, etc., and it is very easy to build a single-page application. Basically, you just need to expose an API and return a JSON response to the client, without rendering the page on the server. On the client, you can organize JSONs with frameworks and display them on the UI. Only sending JSON responses on the server can save bandwidth and improve performance, because you don't need to return layout marks in each response, right, you just need to return pure JSON and then render them on the client.
Let's take a look at my tutorial, which is about how to expose a RESTful API using Express 4. I also wrote another tutorial showing how to combine these APIs with AngularJS.
6. Don't store too much data in Sessions
For typical Express page applications, Session data is saved in memory by default. When you save too much data in the Session, it will significantly increase server overhead. So, either you switch to another storage method to save Session data, or try to minimize the amount of data stored in Session.
For example, when users log in to your app, you can save their IDs only in the Session instead of the entire user data object. Also, for those queries that you can get objects from id, 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 posts on your homepage. You may get data through Mongoose like this:
The code copy is as follows:
Post.find().limit(10).exec(function(err, posts) {
//send posts to client
});
However, the problem is that Mongoose's find() method will query all fields of the object, and many fields are not required on the homepage. For example, commentsis saves replies to specific posts. We don't need to display article replies, so we can remove it when querying. This will undoubtedly increase the speed. The above query can be optimized like this:
The code copy is as follows:
Post.find().limit(10).exclude('comments').exec(function(err, posts) {
//send posts to client
});
8. Use the standard V8 method
Some operations on a collection, such as map, reduce, and forEach, do not necessarily support all browsers. We can solve some browser compatibility issues through the foreground 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 to operate the collection on the server side.
9. Use Nginx in front of 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 on Node. You can compress responses with gzip on nginx to make all responses smaller. So, if you have a product that is operating, I think you should want to use nginx to improve the running speed.
10. Packaging JavaScript
Finally, you can also greatly improve the speed of page application by packaging multiple JS files. When the browser encounters the <script> element in page rendering, it will be blocked and will not continue to run until the script is obtained (unless the 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 these five files are compressed and packaged into one, the overall performance will be greatly improved. The same goes for CSS files. You can use a compilation tool like Grunt/Gulp to package your resource files.
in conclusion
The above 10 tips can definitely improve the speed of your web applications. However, I know there is room for improvement and optimization. If you have any tips for improving performance, let me know in the reply.
Thanks for reading!