Nodejs Debugging Method __js

Source: Internet
Author: User
Tags closure documentation stack trace tainted
   Nodejs internally provides a debug mechanism that allows the program to go into debug mode for developers to analyze code discovery problems step-by-step.
   a total of 3 boot parameters allow the program to enter debug mode, assuming that we want to debug the app.js.
   node Debug app.js
   node--debug app.js
   node--debug-brk app.js

   3 modes have a certain difference in the form of debugging.

   Node Debug App.js
   1. This way to start the program, the program will enter the debug mode, and run to the startup file line 1th Stop, waiting for the developer to release the order to go down.
   2. This way to start the program, directly in the current CMD into the debugging mode.

   node--debug app.js
   1. Start the program this way, the program goes into debug mode, and runs out of all the code. This startup method is often used in the process of starting a program without debugging, by triggering time into the callback function, such as a breakpoint in an HTTP request, waiting for client access to enter the breakpoint.
   2. This way to start the program, will open a TCP port monitoring, in this CMD does not enter the debug mode, you need to open the terminal with node debug command to connect debugging ports. Command for node debug localhost debug port or  node debug p node process ID.

   node--debug-brk app.js
   1. Starting the program in this manner, the program goes into debug mode, but does not run the code until a terminal is connected to the debug port before executing the code and entering the breakpoint at line 1th.
   2. This way to start the program, will open a TCP port monitoring, in this CMD does not enter the debug mode, you need to open the terminal with node debug command to connect debugging ports.

   After you enter debug mode, you can set breakpoints, cancel breakpoints, and control program execution processes with commands. Nodejs support JS native debugging, can be debugger to the next breakpoint. Displays the value of a variable by Console.log (Var). You can also enter REPL under Debug to see the value of the variable.
   node.js Debug Command
Command function
Run Execute script, pause on first line
Restart Re-executing scripts
Cont,c Continue execution until the next breakpoint is encountered
Next, N Single Step execution
Step, S Step Into function
Out, O Step out of the function
Setbreakpoint (), SB () Current line Set Breakpoint
Setbreakpoint (' F () '), SB (...) Set a breakpoint on the first line of function f
Setbreakpoint (' script.js ',), SB (...) Set breakpoints on line 20th of Script.js
Clearbreakpoint, CB (...) Clear All Breakpoints
Cbacktrace, BT Displays the current call stack
List (10) Shows the 10 lines of code that are currently executing
Watch (expr) Add expression expr to watch list
Unwatch (expr) To remove expression expr from the watch list
Watchers Show all expressions and values in the watch list
Repl Open an immediate evaluation environment in the current context
Kill Terminate the currently executing script
Scripts Show all scripts that are currently loaded
Version Show V8 version

Nodejs has supervisor this hot deployment component, Supervisor Plug-ins help us Monitor file changes, automatically restart the server, Supervisor is a Node.js package that is simple to install and can be installed using NPM's installation commands, because we need to run in the console, so we need to install it in the global environment.
NPM install-g Supervisor

   So we can use Supervisor to start the script. Supervisor App we can also debug by Node-inspector, run Node-inspector first, then run node debug app.js.

   Debugging can be related by opening the browser. A good technical article on Nodejs, the address is: http://technosophos.com/2011/10/28/nodejs-debugging-built-debugger.html, the contents are as follows: the HTTP Version of the app worked, but the commandline version did not. What went wrong? It is hard to say. The application simply hung, unresponsive. Try/catch and event handlers didn ' t find anything wrong, with my typical console.log () approach wasn ' t cutting it, either.
   I need to fire up Node.js ' s command line debugger. This is a short tutorial explaining the "debugger" that comes built-in to node.js. It explains the command line debugger to set breakpoints, step through the code, and analyze the debugging out Put.

   By the time you do reading, you should be able to quickly debug your code. The Basics node has a built-in debugger It can be executed using Node debug your_scriptfile.js on your app, you c AnSet breakpoints using Debugger;  Now let's look at each step of debugging ... <!--break--> Set Some Breakpoints A breakpoint is a place in your The code where you want to is able to "fast forward" to inside of the debugger. If you don ' t use a breakpoint, you'll have to step through the code one step in a time.
   And by "The Code", I mean is not only your own code, but Node.js ' s code, as the "as" the code of any packages to you are using.
 In your script, at places near where you are the problem is occurring, you'll want to place some breakpoints:
    Debugger Look at me! I ' m a breakpoint.
    This.emit (' ERROR ', error);
  }
   A Breakpoint is set in the code using the Special keyword debugger. As I understand it, this is a fixture to the V8 engine, not necessarily of node.js.
   You can set as many debugger; Breaks as you want.

   Starting
   up the Debugger to start the Debugger, run your command using node ' s debug argument:node debug Your_scriptfi Le.js. You'll find yourself in a cursor that shows debug. You can type help into the debugger ' s scant help info, or you can type run to run the code.
  Debug> Run
  debugger listening on port 5858connecting ... ok
  breakpoint #1 in #<object>.[ Anonymous] (EXPORTS=#<OBJECT>, require=function require (path) {return
      module._load (path, self);
    Module=#<module> a __filename=/somefile.js:7.
   At any time, you can type quit to quit the debugger.

   Now, have a view into the currently-executing code. The output shows you to the exact line of code this is currently executing (and what file it are found in). Let ' s and how we can navigate.

   Listing Code and generating a Trace the the the-thing you'll likely want to do are get
   your bearings. Where, exactly, are we in the code? To does this, type list. This command prints a formatted and line-numbered segment of code:
  debug> list
   1/*!
   2  * This is a command-line client built with Pronto.
   3  *
   4  * Run it with ' node Apikey.js '. By default, it'll print help text.
   5
   /6 
  => var pronto = require (' pronto ');
   8 var MONGO = require (' Pronto-mongodb ');
   9 var Addapikey = require ('.. /lib/commands/addapikey ');
  Ten var Closure = require (' pronto/lib/commands/closure ');
  One-var Settings = require (' ... /lib/util/settings.js ');
   Here e can, the context, the current line of code. So now we can have a where, in the code, we are. The line marked => are the line currently being executed, and the surrounding lines. But What about the execution stack? How do I get stack trace information?

   I can get this information using the BackTrace command:
  debug> backtrace
  #0 module.js:355:19
  #1 apikey.js:7:14
  #2 module._compile module.js:411:26
  #3 Module._extensions module.js:417:10
  #4 module.load module.js:343:31
  #5 module._load module.js:302:12
  # 6 Module.runmain module.js:430:10
  #7 startup.processnexttick.process._tickcallback node.js:126:26
 While most of the stack above is just core node.js libraries, as we have into our problems, stack traces would provi

   De valuable insight into potential problems by revealing what chain of events led to the current code being executed.

   The next thing we want to be jump to, the Going to Your breakpoint when your start a debugger and execute the Run command, the debugger begins at the The script. Most of the time, this is far away from the section we want to debug. Earlier we set a breakpoint using debugger;.
   Now we want to jump to that breakpoint.  To doing this, we can use the command continue, which tells the debugger to continue until it hits either a breakpoint or the End of the script.
In short, it fast forwards to the next stopping point. 
  Debug> continue
  debug> break in #<object>.[ Anonymous] (EXPORTS=#<OBJECT>, require=function require (path) {return
      module._load (path, self);
    Module=#<module>/myfile.js:157
  Debugger;
  ^
   As we can the "marker on" The last line, we have hit a debugger; Statement. Again, we can get my bearings with list:
  Debug> List
  151   console.log (' Error caught in router ');
  152   Console.log (err);
  153})
  154 
  //console.log (BASECXT)
  156 var cmd = process.argv[2] | | ' Help ';
  ==> Debugger;
  158//Run the command.
  159 try {
  160  router.handlerequest (cmd, basecxt); 
  161}
 This gives us is the context. Now I need to navigate around. In the debugger, you can only step forward. Continue is a fast forward.
   But We have two more modest methods. Step and NEXT We'll look at two navigation commands. The step are short for step into this one, and next are short for move to the next one.
   Sometimes they did the same thing (when there was nothing to step into). Right now, we are are on the debugger; Statement. We can ' t ' Step into ' it (it's not a function or control structure; there's nothing to inspect). So we'll go to the next instruction: 
 debug> next; Break in #<object>. [Anonymous]
    (EXPORTS=#<OBJECT>, require=function require (path) {return module._load (path, self); 
          }, Module=#<module>, foo.js:160 router.handlerequest (cmd, BASECXT); ^ debug> list 154//console.log (BASECXT) 156 var cmd = process.argv[2] | |
  ' Help ';
  157 debugger;
  158//Run the command. 
  159 try {==> router.handlerequest (cmd, BASECXT); 161} 162 catch (e) {163 console.log (' Caught by Try/catch ') 164 console.log (err); 
 next moved us forward to the next statement (Try/catch is ignored). Now we ' re on the line router.handlerequest (cmd, basecxt);.  We can either go over this (next) and move to the next statement, or we can step into it, and the what are happening in the
   HandleRequest () function. Next:go to the next line. Step:step into the details of the current line.
   (Move Down) We want to what are happening inside of HandleRequest (), so we'll step into it: 
 debug> step break in #<router>.handlerequest (Request=get;
                   tainted=undefined),/router.js:71 request = this.resolverequest (request); ^ debug> List *-Reroute * @param string request @param pronto. Context cxt (optional) Router.prototype.handleRequest = function (request, CXT, tainted) {==> Reque
   st = This.resolverequest (request);
   The var spec = This.registry.getRequestSpec (request);
  (spec = = Undefined | | spec = NULL) {+ var err = new Error (' Request not found '); Debug> 
   From the output above, we can have a different file (router.js) looking at the HandleRequest () function.< C1/>from here, we are could step and next we way through the code.
   Using ' print ' to ' Contents ' a Variable
   Finally, there's one more useful debugging trick so can help a grea T deal:at any point during debugging, your can print the content of any variable is scope. For example, where we look at the listing from before, it might being unclear what this has into it at the moment it are used on Line 71. So we can print it and a:
  debug> Print this
  {_events: ' #<object> ', registry: ' #<registry> ', resolver: ' null '}
   Print produces output roughly in the same format as a call to Console.log (). Big objects can have substantial output and but the one above is pretty minimal. And we could further inspect the This.registry object with print, too:
  debug> print this.registry
  {config: ' #<object> ', currentparamname: ' null ', Currentindex: ' 0 ', help: ' #< Object> ', Currentrequestname: '--help '}
   Combining breakpoints, step, Next, List, BackTrace, and print, we can learn all about what are happening in our application During runtime.
   Working with the "CommandLine debugger may" pretty, but it is a functional way to figure out what ' s happening behind The scenes. For those hard-to-find bugs, it's a great tool to know.

Some documentation about NODEJS debugging:
http://www.barretlee.com/blog/2015/10/07/debug-nodejs-in-command-line/
http://i5ting.github.io/node-debug-tutorial/
Http://www.cnblogs.com/tzyy/p/5028348.html
NODEJS Official Debug Documentation: https://nodejs.org/api/debugger.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.