Home  >  Article  >  Web Front-end  >  How to improve the stability of nodejs

How to improve the stability of nodejs

青灯夜游
青灯夜游Original
2022-01-13 17:03:262307browse

Methods to improve the stability of nodejs: 1. Maintain a good code structure; 2. Use "try~catch" to catch exceptions; 3. Use the domain module to handle program exceptions; 4. Use the log4js module to record Log; 5. Use the forever module to manage nodejs.

How to improve the stability of nodejs

The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, DELL G3 computer.

Improve the stability and robustness of the nodejs program

I saw some posts on the Internet and complained about the stability of the nodejs program. why? First, maybe this has something to do with JavaScript. Node is implemented with JavaScript, and JavaScript is also known as "the most misunderstood language in the world." We can take a look at what the founder of nodejs said, and we can take a look. In this article, why does node use javascript to implement it? Secondly, nodejs is still young after all, and the official website also marks the current status of this module in some modules.

I took some time to think about this issue in the past two days. I think the first function of our program should be independent. If one function is abnormal, it should not affect another normal function. It should not Crash the entire program. Secondly, even if the program crashes, we should have a program to start automatically. In addition, we should record logs to facilitate us to track the problem. I think the stability of nodejs can be improved mainly from the following aspects:

1) Maintain a good code structure:

We know that node is single-threaded, non-blocking io, default It is asynchronous, and the subsequent processes are processed through callbacks. If there are too many nested levels, it will inevitably cause confusion in the logical structure of the code, and is not conducive to maintenance and upgrades. You can use async, an asynchronous process control module, to clarify our code logic.

2) Use process.on('uncaughtException', function(err){...}); to handle uncaught errors.

3) Use try~catch to catch exceptions:

This can only solve part of the problem, not everything. As mentioned above, node is a single Thread, non-blocking io, asynchronous by default, handles subsequent processes through callbacks. try~catch cannot capture the error in the callback. How to capture the error in the callback? You can use the domain module

4) Use the domain module to handle program exceptions

Let’s first look at the explanation of domain: domain is a subclass of the EventEmitter class. Listen to its error event to handle the errors it captures. It provides a way to handle multiple different IO operations as a single group. If any event trigger or callback registered to the domain triggers an 'error' event, or throws an error, the domain object will be notified. Instead of directly losing the context of this error from the `process.on('uncaughtException')' handler, it will not cause the program to exit immediately because of this error accompanied by an error code.

How to use the domain module? Look at an example:

serverDomain.run(function() {
  // 服务器在serverDomain的作用域内被创建
  http.createServer(function(req, res) {
    // req和res同样在serverDomain的作用域内被创建
    // 但是,我们想对于每一个请求使用一个不一样的域。
    // 所以我们首先创建一个域,然后将req和res添加到这个域上。
    var reqd = domain.create();
    reqd.add(req);
    reqd.add(res);
    reqd.on('error', function(er) {
      console.error('Error', er, req.url);
      try {
        res.writeHead(500);
        res.end('Error occurred, sorry.');
      } catch (er) {
        console.error('Error sending 500', er, req.url);
      }
    });
  }).listen(1337);    
});
```

Description: First create a domain (domain.create()), then add the distributor that needs to be monitored to the domain, and finally bind an error event to the domain, so that you can Monitored.

Look at another example:

var d = domain.create();
d.on('error', function(er) {
  console.error('Caught error!', er);
});
d.run(function() {
  process.nextTick(function() {
    setTimeout(function() { // 模拟几个不同的异步的东西
      fs.open('non-existent file', 'r', function(er, fd) {
        if (er) throw er;
        // 继续。。。
      });
    }, 100);
  });
});

Instructions: First create a domain, bind an error event to the domain, and then provide functions that can be run in the context of the domain

If What about callbacks? You can use it like this

var d = domain.create();

function readSomeFile(filename, cb) {
  fs.readFile(filename, 'utf8', d.bind(function(er, data) {
    // if this throws, it will also be passed to the domain
    return cb(er, data ? JSON.parse(data) : null);
  }));
}

d.on('error', function(er) {
  // an error occurred somewhere.
  // if we throw it now, it will crash the program
  // with the normal line number and stack message.
});

Of course you can also use it like this

var d = domain.create();

function readSomeFile(filename, cb) {
  fs.readFile(filename, 'utf8', d.bind(function(er, data) {
    // if this throws, it will also be passed to the domain
    return cb(er, data ? JSON.parse(data) : null);
  }));
}

d.on('error', function(er) {
  // an error occurred somewhere.
  // if we throw it now, it will crash the program
  // with the normal line number and stack message.
});

This function is almost exactly the same as domain.bind(callback). However, in addition to catching errors being thrown, it also intercepts the Error object passed to this function as the first argument.

5) Use the log4js module to record logs

Log4js is a very powerful log management tool. You can check out this github project: https://github.com /nomiddlename/log4js-node

6) Use the forever module to manage nodejs

Forever is a module for server-side management of nodejs, a command line tool that can be started. Stop the app. Forever is completely based on command line operations. Under the management of the forever process, a sub-process of the node is created, and the running status of the node sub-process is monitored through the monitor. Once the file is updated or the process hangs, forever will automatically restart the node server to ensure that the application is normal. run. Very easy to use.

You can pay attention to this project: https://github.com/nodejitsu/forever

But forever is not a panacea, and it also suffers from the following problems:

  • Limited monitoring and logging functions
  • Poor support for process management configuration
  • No support for clusters
  • The code base is aging (meaning that after upgrading node.js Frequent failures)

Attached to this article is the test code: https://github.com/yupeng528/node-error

For more node-related knowledge, please visit: nodejs tutorial! !

The above is the detailed content of How to improve the stability of nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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