To make front-end work more efficient, you must thoroughly master some necessary debugging skills. Native debugging is most commonly used during Node application development, but once your code is in production, you must adopt other strategies to track and resolve problems.

In programming, there is a term “post-mortem debugging,” which means debugging after a program crashes. For Node applications, you can use this solution if you encounter problems that are difficult to reproduce or debug in your online environment. Online problems are usually urgent, so we want to be able to locate the code that caused the problem the fastest.

So how do we do that? Here’s a simple example.

Collect crash information

Suppose you now have code like this:

const demo = (data) = > {
        const {id, profile} = person;
        console.log(id);
        console.log(profile.name);
}

demo({id: 1.profile: {age: 12}});
Copy the code

After running it will report an error and exit. What you need to do is collect information about the collapse and analyze it. Core Dump is a tool used to record the running information of programs. It contains the memory status and call stack during the running process of programs. It can restore the “crime scene” at that time most realistically.

How do we get Core Dump files in Node.js?

First, let’s set the kernel limits on the system:

ulimit -c unlimited
Copy the code

Then you need to start the application with the –abort-on-uncaught-exception flag to manually trigger the writing of the core file after the application crashes:

node --abort-on-uncaught-exception app.js
Copy the code

When the program crashes, it generates a file like core.81371 in the /cores directory for Linux or MAC systems. This file is the core we use to debug the crash investigation program.

If your application is in the middle of execution, we can also manually capture core dump files, which is similar to real-time inspection, mainly used for application states such as suspended animation.

To capture the process manually, you need to use the Linux gcore command to find the pid of the current process (for example, 123) and run the following command:

gcore 123
Copy the code

Generate the corresponding core dump file.

Another method is to use the LLDB debugging tool. Run the LLDB command to install the LLDB on the MAC operating system.

brew install --with-lldb --with-toolchain llvm
Copy the code

Then execute:

lldb --attach-pid <pid> -b -o 'process save-core' "core.<pid>"'
Copy the code

This allows you to export core dump files for a particular process without restarting the program.

Commissioning procedures

With the core dump file in place, it’s time to debug and analyze.

First, you need to use a handy analysis tool. You can choose mDB_V8 or LLNode. Both tools are similar in use.

This section uses llnode as an example to introduce the following commands:

The command meaning
v8 help Viewing Help Information
v8 bt Get stack trace at crash View stack information
v8 souce list Display stack Frame source code
v8 inspect View the object content of the corresponding address
frame select Select the corresponding Stack frame

To do this, use llNode to load the core file:

llnode -c /cores/core.81371
Copy the code

Then get the corresponding stack information:

// Check the stack information (llNode) v8 bt Inspect (llNode) v8 inspect (llNode) frame select 6 (llNodesource list
Copy the code

Finally, by combining the stack information with the source code, you can find out why the error occurred.

A memory leak

In addition to apps crashing, sometimes you’ll find that apps start to slow down as they run longer. This could be a memory leak.

Take this code for example:

const requests = new Map(a); app.get("/", (req, res) => {
  requests.set(req.id, req);
  res.status(200).send("hello")})Copy the code

In general, memory leaks tend to occur in scenarios such as closures. To debug memory leaks, use the following commands:

node --trace_gc --trace_gc_verbose app.js
Copy the code

After starting the application, run the following command using the pressure test tool:

ab -k -c200 -n10000000 http://localhost:3000
Copy the code

You can see that memory usage increases as the program runs.

Alternatively, we can use the heap snapshot to retrieve snapshot information:

process.on('SIGUSR2', () => {
	const { writeHeapSnapshot } = require("v8");
	
	console.log("Heap snapshot has written:", writeHeapSnapshot())
})
Copy the code

Execute from the command line:

kill -SIGUSR2 <pid>
Copy the code

You can then use the Memory menu of Chrome Devtools to load the corresponding snapshot file for comparison.

If you are in development, you can also launch the app directly in debug mode:

node --inspect app.js
Copy the code

Then use the menu Devtools > Memory > Take Heap Snapshot to get the snapshot file.

By comparing two different memory snapshots, we can quickly find the object with the fastest memory growth, and then analyze the corresponding source code to see where the problem is.

In addition to using Chrome, you can also use the versatile LLNode debugger for memory leak analysis on Linux hosts. The principle is basically the same, again by analyzing core files, and then installing object size sort, for suspicious object source view.

(llnode) v8 findjsobjects
(llnode) v8 findjsinstances -d <Object>
(llnode) v8 inspect -m <address》
(llnode) v8 findrefs <address>
Copy the code

Other strategies

Another strategy for collecting reports is to use parameters, for versions 13.0 and above:

node \
	--experimental-report \
	--diagnostic-report-uncaught-exception \
	--diagnostic-report-on-fatalerror \
	app.js
Copy the code

This way, when the application crashes, the corresponding report can be retrieved. You can also explicitly control the output file name of the report with code such as:

process.report.writeReport('./foo.json');

Copy the code

For more information, please refer to the official documentation: nodejs.org/api/report….

— Reprint please indicate the source —

Scan the QR code on wechat and follow my official account

Finally, welcome everyone to pay attention to my public number, learn to communicate together.

The resources

Medium.com/netflix-tec… En.wikipedia.org/wiki/Debugg… www.bookstack.cn/read/node-i… Github.com/bnoordhuis/…