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.
Using uncaughtException
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.
Using try/catch
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.
Integrated into the framework
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 + '
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.
Guarding the NodeJS process and recording error logs
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.
Use node to guard node
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
