Home > Article > Web Front-end > How to solve NodeJS service always crashes
This article will introduce to you how to solve the problem of NodeJS service always crashing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Many people have such an image, NodeJS is faster; but because it is single-threaded, it is unstable, a bit unsafe, and not suitable for handling complex businesses; It is more suitable for simple business scenarios with high concurrency requirements.
In fact, NodeJS does have a "fragile" side. An "unhandled" exception generated somewhere in a single thread will indeed cause the entire Node.JS to crash and exit. Let's look at an example. Here is one The file of node-error.js:
var http = require('http'); var server = http.createServer(function (req, res) { //这里有个错误,params 是 undefined var ok = req.params.ok; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World '); }); server.listen(8080, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8080/');
Start the service and test it in the address bar and find http://127.0.0.1:8080/ As expected, node crashed
$ node node-error Server running at http://127.0.0.1:8080/ c:githubscript ode-error.js:5 var ok = req.params.ok; ^ TypeError: Cannot read property 'ok' of undefined at Server.<anonymous> (c:githubscript ode-error.js:5:22) at Server.EventEmitter.emit (events.js:98:17) at HTTPParser.parser.onIncoming (http.js:2108:12) at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23) at Socket.socket.ondata (http.js:1966:22) at TCP.onread (net.js:525:27)
Why What's the solution?
In fact, with the development of Node.JS today, if it can’t even solve this problem, then no one will probably use it long ago.
We can use uncaughtException to globally capture uncaught Errors. At the same time, you can also print out the call stack of this function. After capture, it can effectively prevent the node process from exiting. For example:
process.on('uncaughtException', function (err) { //打印出错误 console.log(err); //打印出错误的调用栈方便调试 console.log(err.stack); });
This is equivalent to guarding inside the node process, but many people do not advocate this method, which means that you cannot fully control the exceptions of Node.JS.
We can also add try/catch before the callback to also ensure thread safety.
var http = require('http'); http.createServer(function(req, res) { try { handler(req, res); } catch(e) { console.log(' ', e, ' ', e.stack); try { res.end(e.stack); } catch(e) { } } }).listen(8080, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8080/'); var handler = function (req, res) { //Error Popuped var name = req.params.name; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello ' + name); };
The advantage of this solution is that the error and call stack can be output directly to the web page where it currently occurs.
Standard HTTP response processing will go through a series of Middleware (HttpModule) and finally reach the Handler, as shown in the following figure:
These Middleware and Handler have one feature in NodeJS. They are all callback functions, and the callback function is the only place where Node will crash during runtime. According to this feature, we only need to integrate a try/catch in the framework to solve the exception problem relatively perfectly, and it will not affect other users' requests.
In fact, almost all current NodeJS WEB frameworks do this. For example, WebSvr
, which OurJS open source blog is based on, has such an exception handling code:
Line: 207 try { handler(req, res); } catch(err) { var errorMsg = ' ' + 'Error ' + new Date().toISOString() + ' ' + req.url + ' ' + err.stack || err.message || 'unknow error' + ' ' ; console.error(errorMsg); Settings.showError ? res.end('<pre class="brush:php;toolbar:false">' + errorMsg + '') : res.end(); }
So what to do about errors that are not generated in callbacks? Don't worry, in fact, such a node program cannot be started at all.
In addition, node’s own cluster also has a certain fault tolerance. It is very similar to nginx’s worker, but consumes slightly more resources (memory) and programming is not very convenient. OurJS does not adopt this design.
The problem of Node.JS crashing due to exceptions has been basically solved. However, no platform is 100% reliable, and there are still some errors. Some exceptions thrown from the bottom layer of Node cannot be caught by try/catch and uncaughtException. When running ourjs before, I would occasionally encounter file stream reading exceptions thrown by the underlying layer. This was a BUG of the underlying libuv. Node.js was fixed in 0.10.21.
Faced with this situation, we should add a daemon process to the nodejs application so that NodeJS can be revived immediately after encountering an abnormal crash.
In addition, these exceptions should be recorded in the log so that the exceptions never happen again.
node-forever provides guarding and LOG logging functions.
It is very easy to install
[sudo] npm install forever
It is also very simple to use
$ forever start simple-server.js $ forever list [0] simple-server.js [ 24597, 24596 ]
You can also read the log
forever -o out.log -e err.log my-script.js
Use shell to start the script to protect the node
Using node to guard the resource overhead may be a bit large, and it will also be a little complicated. OurJS starts the script directly at boot to guard the process thread.
For example, the ourjs startup file placed in debian: /etc/init.d/ourjs
This file is very simple, with only startup options. The core function of the guardian is an infinite loop while true; To prevent too many errors from blocking the process, the service is restarted every 1 second after each error.
WEB_DIR='/var/www/ourjs' WEB_APP='svr/ourjs.js' #location of node you want to use NODE_EXE=/root/local/bin/node while true; do { $NODE_EXE $WEB_DIR/$WEB_APP config.magazine.js echo "Stopped unexpected, restarting " } 2>> $WEB_DIR/error.log sleep 1 done
Error logging is also very simple. Directly enter the process console Just output the error to the error.log file: 2>> $WEB_DIR/error.log In this line, 2 represents Error.
Recommended learning: javascript video tutorial
The above is the detailed content of How to solve NodeJS service always crashes. For more information, please follow other related articles on the PHP Chinese website!