Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to improve the stability of nodejs

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to improve the stability of nodejs, the article is very detailed, has a certain reference value, interested friends must read it!

Methods to improve the stability of nodejs: 1, maintain a good code structure; 2, use "try~catch" to catch exceptions; 3, use domain module to handle program exceptions; 4, use log4js module to log; 5, use forever module to manage nodejs.

This tutorial operating environment: windows7 system, nodejs version 12.19.0, DELL G3 computer.

Improve the stability and robustness of nodejs programs

See some posts on the Internet, spit bad, question 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 the statement of the founder of nodejs, we can take a look at this article of Zhihu, why is node implemented with javascript? second, nodejs is still young after all, and the official website also marks the current status of this module in some modules.

In the past two days, I took some time to think about this problem. I think the first function of our program should be independent, that is, one function is abnormal, it should not affect another normal function, and the whole program should not collapse. Secondly, even if the program crashes, we should have one to start the program automatically. in addition, we should record logs to make it easier for us to track problems. 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, the default is asynchronous, through callback to deal with the following process, if there are too many levels of nesting, it is bound to cause confusion in the logical structure of the code, and it is not conducive to maintenance and upgrade. We can use async, an asynchronous process control module, to sort out 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, because node is single-threaded, non-blocking io, the default is asynchronous, through callback to deal with the following process, try~catch can not catch the error of error in callback, how to catch the error in callback? You can use the domain module

4) use domain module to handle program exceptions

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

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

ServerDomain.run (function () {/ / server is created within the scope of serverDomain (function (req, res) {/ / req and res are also created within the scope of serverDomain / / but we want to use a different domain for each request. / / so we first create a domain, and then add req and res to the domain. 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) }) (1337);}); ```

Description: first create a domain (domain.create ()), then add the dispatcher to the domain that needs to be monitored, and finally bind an error event to the domain so that it can be monitored.

Look at another example:

Var d = domain.create (); d.on ('error', function (er) {console.error (' Caught errorproof, er);}); d.run (function () {process.nextTick (function () {setTimeout (function () {/ / simulate several different asynchronous things fs.open ('non-existent file',' rsectors, function (er, fd) {if (er) throw er) / / continue. });}, 100);})

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

What about the callback? It can be used this way.

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, it can also be used in this way.

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 identical to domain.bind (callback). However, in addition to catching errors that are thrown, it also intercepts the Error object that is passed to the function as the first argument.

5) use log4js module to log

Log4js is a very powerful log management tool, you can take a look at the github project: https://github.com/nomiddlename/log4js-node

6) use forever module to manage nodejs

Forever is a module of server-side management nodejs, a command-line tool that can start and stop app applications. Forever is entirely based on the command line operation. Under the management of the forever process, create a child process of node and monitor the operation of the node child process through monitor. Once the file is updated or the process dies, forever will automatically restart the node server to ensure the normal operation of the application. It's very easy to use.

You can follow this project: https://github.com/nodejitsu/forever

But forever is not a panacea. It is also caused by the following questions:

Limited monitoring and logging capabilities

Poor support for process management configuration

Cluster is not supported

Code base aging (meaning frequent failures when upgrading node.js)

The above is all the content of this article "how to improve the stability of nodejs". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report