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 + '') : 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.
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!

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

The application of React in HTML improves the efficiency and flexibility of web development through componentization and virtual DOM. 1) React componentization idea breaks down the UI into reusable units to simplify management. 2) Virtual DOM optimization performance, minimize DOM operations through diffing algorithm. 3) JSX syntax allows writing HTML in JavaScript to improve development efficiency. 4) Use the useState hook to manage state and realize dynamic content updates. 5) Optimization strategies include using React.memo and useCallback to reduce unnecessary rendering.

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React is a JavaScript library for building user interfaces, suitable for large and complex applications. 1. The core of React is componentization and virtual DOM, which improves UI rendering performance. 2. Compared with Vue, React is more flexible but has a steep learning curve, which is suitable for large projects. 3. Compared with Angular, React is lighter, dependent on the community ecology, and suitable for projects that require flexibility.

React operates in HTML via virtual DOM. 1) React uses JSX syntax to write HTML-like structures. 2) Virtual DOM management UI update, efficient rendering through Diffing algorithm. 3) Use ReactDOM.render() to render the component to the real DOM. 4) Optimization and best practices include using React.memo and component splitting to improve performance and maintainability.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor