稳定性: 2 - 稳定

    Node.js 包含了一个进程外的调试实用程序,可通过 [V8 检查器][V8 Inspector]或内置的调试客户端访问。 要使用它,请使用 inspect 参数启动 Node.js,并带上要调试的脚本的路径。 如果出现提示符,则表明调试器已成功启动:

    1. $ node inspect myscript.js
    2. < Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
    3. < For help, see: https://nodejs.org/en/docs/inspector
    4. < Debugger attached.
    5. Break on start in myscript.js:1
    6. > 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
    7. 2 setTimeout(() => {
    8. 3 console.log('world');
    9. debug>

    Node.js 的调试器客户端不是一个具有全部特性的调试器,但可以进行简单的单步执行和调试。

    debugger; 语句插入到脚本的源代码,则将会在代码中的该位置启用一个断点:

    1. // myscript.js
    2. global.x = 5;
    3. setTimeout(() => {
    4. debugger;
    5. console.log('世界');
    6. }, 1000);
    7. console.log('你好');

    一旦执行调试器,则将会在第 3 行出现一个断点:

    1. $ node inspect myscript.js
    2. < Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
    3. < For help, see: https://nodejs.org/en/docs/inspector
    4. < Debugger attached.
    5. Break on start in myscript.js:1
    6. > 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
    7. 2 setTimeout(() => {
    8. 3 debugger;
    9. debug> cont
    10. < 你好
    11. break in myscript.js:3
    12. 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
    13. 2 setTimeout(() => {
    14. > 3 debugger;
    15. 4 console.log('世界');
    16. 5 }, 1000);
    17. debug> next
    18. break in myscript.js:4
    19. 2 setTimeout(() => {
    20. 3 debugger;
    21. > 4 console.log('世界');
    22. 5 }, 1000);
    23. 6 console.log('你好');
    24. debug> repl
    25. Press Ctrl + C to leave debug repl
    26. > x
    27. 5
    28. > 2 + 2
    29. 4
    30. debug> next
    31. < 世界
    32. break in myscript.js:5
    33. 3 debugger;
    34. 4 console.log('世界');
    35. > 5 }, 1000);
    36. 6 console.log('你好');
    37. 7
    38. debug> .exit

    repl 命令允许远程地运行代码。 next 命令会单步进入下一行。 键入 help 可以查看其他可用的命令。

    在不键入命令的情况下按 enter 键,则会重复上一个调试器命令。