Home > Web Front-end > JS Tutorial > 10 Tips to Make Node.js Applications Faster_node.js

10 Tips to Make Node.js Applications Faster_node.js

WBOY
Release: 2016-05-16 15:06:44
Original
1475 people have browsed it

NodeJS is a server-side JavaScript interpreter that will change the concept of how servers should work. Its goal is to help programmers build highly scalable applications and write code that can handle tens of thousands of simultaneous connections to one (and only one) physical machine.

Node.js is already fast thanks to its event-driven and asynchronous nature. However, just being fast is not enough in modern networks. If you're going to use Node.js to develop your next web application, then you should do whatever it takes to make your application faster, blazingly fast. This article will introduce 10 tested tips that can greatly improve Node applications. Without further ado, let’s look at them 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 that on the Dashboard page, you want to execute the following calls:

User information -getUserProfile().

Current activity -getRecentActivity().

Subscription content -getSubscriptions().

Notification content -getNotifications().

To get this information, you should create independent 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 ends. A possible solution is to call them in parallel.

As you know Node.js is very good at calling multiple methods in parallel due to its asynchronicity. We cannot waste our resources. Those methods I mentioned above have no dependencies so we can execute them in parallel. In this way we can reduce the amount of middleware and greatly increase the speed.

We can use async.js to handle parallelism, which is a Node module specially used to tune JavaScript asynchronously. The following code demonstrates how to use async.js to call multiple methods in parallel:

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

If you want to learn more about async.js, please visit its GitHub page.

2. Asynchronous

Node.js is single-threaded by design. Based on this, synchronous code can clog the entire application. For example, most file system APIs have their synchronous versions. The following code demonstrates both synchronous and asynchronous operations of file reading:

// Asynchronous
fs.readFile('file.txt', function(err, buffer) {
var content = buffer.toString();
});
// Synchronous
var content = fs.readFileSync('file.txt').toString();
Copy after login

But if you perform 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 ensure that your code is using the asynchronous version of the API. 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 eliminate synchronization operations from your code, a synchronous call from an external library will make all your efforts wasted and reduce your application performance

3. Caching

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 posts and displaying them:

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 });
});
});
Copy after login

If you don’t post often, you can cache the list of posts and clear them after a period of time. For example, we can use the Redis module to achieve this purpose. Of course, you must have Redis installed on your server. You can then use a client called node_redis to save the key/value pairs. 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 });
});
});
});
Copy after login

See, let’s first check the Redis cache to see if there is a post. If there are, we get the list of posts from the cache. Otherwise we retrieve the database contents and cache the results. Additionally, after a certain amount of time, we can clear the Redis cache so the content can be updated.

4.gzip compression

Enabling gzip compression can have a huge impact on your web application. When a gzip-compressed browser requests some resource, the server compresses the response before returning it to the browser. If you don't gzip 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. Additionally, static content can be compressed and processed using compression middleware. The following is a usage example:

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

5.尽量在客户端渲染

现在有超多功能强劲的客户端 MVC/MVVM 框架,比如说 AngularJS, Ember, Meteor, 等等,构建一个单页面应用变得非常简单。基本上,你只要公开一个 API,返回 JSON 响应给客户端就可以了,而不需要在服务端渲染页面。

在客户端,你可以用框架来组织 JSON 然后把它们显示在 UI 上。服务端只发送 JSON 响应可以节省带宽,改善性能,因为你不需要在每个响应里面都返回布局标记了,对吧,你只需要返回纯 JSON,然后在客户端渲染它们。

6.不要在Session存储太多数据

典型的 Express 页面应用, Session 数据默认是保存在内存中的。当你把太多数据保存在 Session 的时候,会导致服务器开销显著增大。所以,要么你切换到别的储存方式来保存 Session 数据,要么尽量减少存储在 Session 中的数据量。

比如说,当用户登录到你的应用的时候,你可以只在 Session 中保存他们的 ID 而不是整个用户数据对象。还有,对于那些你能够从 id 拿到对象的查询,你应该会喜欢用 MongoDB 或者 Redis 来存储 session 数据。

7.优化查询

假设你有个博客,你要在主页上显示最新帖子。你可能会通过 Mongoose 这样取数据:

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

不过问题是 Mongoose 的 find() 方法会把对象的所有字段都查询出来,而许多字段在主页上并不要求。比如说,commentsis 保存的是特定帖子的回复。我们不需要显示文章回复,所以我们可以在查询的时候把它给剔除掉。这无疑会提高速度。可以像这样优化上面那条查询:

Post.find().limit(10).exclude('comments').exec(function(err, posts) {
//send posts to client
});
Copy after login

8.用标准的V8方法

集合上的一些操作,比如 map,reduce,和 forEach 不一定支持所有浏览器。我们可以通过前台的库解决部分浏览器兼容性问题。但对于 Node.js,你要确切知道 Google 的 V8 JavaScript 引擎支持哪些操作。这样,你就可以在服务端直接用这些内建方法来操作集合了。

9.在 Node 前面用 Nginx

Nginx 是个微小型轻量 Web 服务器,用它可以降低你的 Node.js 服务器的负载。你可以把静态资源配置到 nginx 上,而不是在 Node 上。你可以在 nginx 上用 gzip 压缩响应,让所有的响应都变得更小。所以,如果你有个正在营运的产品,我觉得你应该会想用 nginx 来改善运行速度的。

10.打包JavaScript

最后,你还可以大大提高页面应用速度,通过把多个 JS 文件打包。当浏览器在页面渲染中碰到 元素的时候会被堵塞,直到拿到这个脚本才继续运行(除非设置了异步属性)。比如,如果你的页面有五个 JavaScript 文件,浏览器会发出五个独立的 HTTP 请求来获取他们。如果把这五个文件压缩打包成一个,整体性能将可以大幅提升。CSS 文件也是一样。你可以用诸如 Grunt/Gulp 这样的编译工具来打包你的资源文件。

通过以上十个方面给大家介绍了Node.js 应用跑得更快的技巧,希望对大家有所帮助!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template