How to debug a nodejs program? The following article will introduce you to the nodejs debugging method. I hope it will be helpful to you!
For developers, in the process of developing applications, they often need to resort to the debugging function of the programming language for the convenience of development and to solve bugs. Generally speaking, we need to use the debugging function of a powerful IDE to complete this work. nodejs is no exception.
Today we will introduce in detail how to debug the node program.
Enable nodejs debugging
Do you remember the koa program we talked about before? This article will take a simple koa server program as an example to start debugging nodejs.
Let’s first look at a simple koa service app.js:
const Koa = require('koa'); const app = module.exports = new Koa(); app.use(async function(ctx) { ctx.body = 'Hello World'; }); if (!module.parent) app.listen(3000);
The above program opens port 3000 and establishes an http service. Every time a request is made, hello World will be returned, which is very simple.
To run the above program, we need to execute node app.js. This will execute app.js but will not enable debugging.
How to debug?
We need to add the --inspect parameter:
node --inspect app.js
The above code will enable the debugging function of nodejs.
Let’s take a look at the output:
Debugger listening on ws://127.0.0.1:9229/88c23ae3-9081-41cd-98b0-d0f7ebceab5a For help, see: https://nodejs.org/en/docs/inspector
The results tell us two things. The first thing is the port that the debugger listens to. By default, port 9229 of 127.0.0.1 will be opened. And assigned a unique UUID for differentiation.
The second thing is to tell us that the debugger used by nodejs is Inspector.
Inspector was introduced after nodejs 8. If it is before nodejs 7, then the legacy debugger is used.
Debugging security
If the debugger is connected to the nodejs running environment, if there is a malicious attacker, the malicious attacker can run arbitrary code in the nodejs environment . This will bring great security risks to our program.
So we must pay attention to the safety of debugging. Generally speaking, we do not recommend remote debugging.
By default, --inspect is bound to 127.0.0.1, which only allows local programs to access. And any locally running program has permission to debug the program.
If we really want to expose the debug program to external programs, we can specify the external IP address of the machine or 0.0.0.0 (indicating any address, no restrictions), so that the remote machine can perform remote Debugged.
What should we do if we want to perform safe remote debugging?
First, we need to enable local debugging:
node --inspect app.js
Then we can build an ssh tunnel to map the local 9221 port to the remote server's 9229 port:
ssh -L 9221:localhost:9229 user@remote.example.com
In this way, we can perform remote debugging by connecting to the local 9221 port.
Use WebStorm for nodejs debugging
WebStorm produced by JetBrains can be said to be a powerful tool for developing nodejs. WebStorm has its own debug option. If this option is turned on, it will Turn on --inspect:
Using WebStorm for debugging is similar to using IDEA for java program debugging, so I won’t go into details here.
Use Chrome devTools for debugging
The prerequisite for using Chrome devTools for debugging is that we have turned on the --inspect mode.
Enter chrome://inspect in chrome:
We can see the chrome inspect interface. If you already have a nodejs program that has inspect enabled locally, If so, you can see it directly in Remote Target.
Select the target you want to debug and click inspect to open the Chrome devTools debugging tool:
You can profile the program and debug it. .
Here we are focusing on debugging, so go to the source column and add the source code of the program you want to debug:
Just add a breakpoint Debugging started. It is the same as debugging js on the web side in chrome.
Use node-inspect for debugging
In fact, nodejs has a built-in debugging tool called node-inspect, which is a cli debugging tool. Let's see how to use it.
We directly use:
node inspect app.js < Debugger listening on ws://127.0.0.1:9229/f1c64736-47a1-42c9-9e9e-f2665073d3eb < For help, see: https://nodejs.org/en/docs/inspector < Debugger attached. Break on start in app.js:1 > 1 const Koa = require('koa'); 2 const app = module.exports = new Koa(); 3 debug>
node inspect does two things. The first thing is to generate a subroutine to run node --inspect app.js. The second thing is to Run the CLI debug window in the program.
This CLI debugger provides us with some very useful commands:
1, Stepping
- cont, c : Continue to execute
- next, n: Step to the next step
- step, s: Step in
- out, o: Step out
- pause: Pause Running code
2, Breakpoints
- setBreakpoint(), sb(): Set a breakpoint on the current line
- setBreakpoint(line), sb(line): Set a breakpoint on the specified line
- setBreakpoint ('fn()'), sb(…): Set a breakpoint in the specified function
- setBreakpoint('script.js', 1), sb(…): Set it in the specified script file Breakpoint
- clearBreakpoint('script.js', 1), cb(…): Clear breakpoint from the file
3, Information
- backtrace, bt: Print the backtrace information of the current execution frame
- list(5): List the 5 lines before and after the source code
- watch(expr): Add a monitor Expression
- unwatch(expr): Delete the watch expression
- watchers: List all watchers
- repl: Open the repl expression
- exec expr : Execute expression
Through the above command, we can perform more complex debugging activities in the CLI.
Other debug clients
In addition to the ones we mentioned above, we can also use vscode, Visual Studio, Eclipse IDE, etc. to perform nodejs Debugging will not be introduced in detail here.
Interested friends can explore on their own.
For more node-related knowledge, please visit: nodejs tutorial! !
The above is the detailed content of How to enable nodejs debugging? How to debug nodejs program?. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

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

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

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment