Debug node js windows

Содержание
  1. Node.js v15.14.0 documentation
  2. Debugger #
  3. Watchers #
  4. Command reference #
  5. Stepping #
  6. Breakpoints #
  7. Information #
  8. Execution control #
  9. Various #
  10. Advanced usage #
  11. V8 inspector integration for Node.js #
  12. Debugging Guide
  13. Enable Inspector
  14. Security Implications
  15. Exposing the debug port publicly is unsafe
  16. Local applications have full access to the inspector
  17. Browsers, WebSockets and same-origin policy
  18. Inspector Clients
  19. node-inspect
  20. Chrome DevTools 55+, Microsoft Edge
  21. Visual Studio Code 1.10+
  22. Visual Studio 2017
  23. JetBrains WebStorm 2017.1+ and other JetBrains IDEs
  24. chrome-remote-interface
  25. Gitpod
  26. Eclipse IDE with Eclipse Wild Web Developer extension
  27. Command-line options
  28. Enabling remote debugging scenarios
  29. Legacy Debugger
  30. Built-in Debugger
  31. node-inspector
  32. Руководство по отладке
  33. Активация инспектора
  34. Последствия для безопасности
  35. Публичное обличение порта отладки небезопасно
  36. Локальные приложения имеют полный доступ к инспектору
  37. Браузеры, WebSockets, same-origin policy
  38. Клиенты инспектора
  39. node-inspect
  40. Инструменты разработчика Chrome 55+, Microsoft Edge
  41. Visual Studio Code 1.10+
  42. Visual Studio 2017
  43. JetBrains WebStorm 2017.1+ и другие IDE JetBrains
  44. chrome-remote-interface
  45. Gitpod
  46. Eclipse IDE c расширением Eclipse Wild Web Developer
  47. Аргументы командной строки
  48. Включение сценариев удаленной отладки
  49. Устаревший Debugger
  50. Встроенный отладчик
  51. node-inspector

Node.js v15.14.0 documentation

Debugger #

Node.js includes an out-of-process debugging utility accessible via a V8 Inspector and built-in debugging client. To use it, start Node.js with the inspect argument followed by the path to the script to debug; a prompt will be displayed indicating successful launch of the debugger:

The Node.js debugger client is not a full-featured debugger, but simple step and inspection are possible.

Inserting the statement debugger; into the source code of a script will enable a breakpoint at that position in the code:

Once the debugger is run, a breakpoint will occur at line 3:

The repl command allows code to be evaluated remotely. The next command steps to the next line. Type help to see what other commands are available.

Pressing enter without typing a command will repeat the previous debugger command.

Watchers #

It is possible to watch expression and variable values while debugging. On every breakpoint, each expression from the watchers list will be evaluated in the current context and displayed immediately before the breakpoint’s source code listing.

To begin watching an expression, type watch(‘my_expression’) . The command watchers will print the active watchers. To remove a watcher, type unwatch(‘my_expression’) .

Command reference #

Stepping #

  • cont , c : Continue execution
  • next , n : Step next
  • step , s : Step in
  • out , o : Step out
  • pause : Pause running code (like pause button in Developer Tools)

Breakpoints #

  • setBreakpoint() , sb() : Set breakpoint on current line
  • setBreakpoint(line) , sb(line) : Set breakpoint on specific line
  • setBreakpoint(‘fn()’) , sb(. ) : Set breakpoint on a first statement in function’s body
  • setBreakpoint(‘script.js’, 1) , sb(. ) : Set breakpoint on first line of script.js
  • setBreakpoint(‘script.js’, 1, ‘num , sb(. ) : Set conditional breakpoint on first line of script.js that only breaks when num evaluates to true
  • clearBreakpoint(‘script.js’, 1) , cb(. ) : Clear breakpoint in script.js on line 1

It is also possible to set a breakpoint in a file (module) that is not loaded yet:

It is also possible to set a conditional breakpoint that only breaks when a given expression evaluates to true :

Information #

  • backtrace , bt : Print backtrace of current execution frame
  • list(5) : List scripts source code with 5 line context (5 lines before and after)
  • watch(expr) : Add expression to watch list
  • unwatch(expr) : Remove expression from watch list
  • watchers : List all watchers and their values (automatically listed on each breakpoint)
  • repl : Open debugger’s repl for evaluation in debugging script’s context
  • exec expr : Execute an expression in debugging script’s context

Execution control #

  • run : Run script (automatically runs on debugger’s start)
  • restart : Restart script
  • kill : Kill script

Various #

  • scripts : List all loaded scripts
  • version : Display V8’s version

Advanced usage #

V8 inspector integration for Node.js #

V8 Inspector integration allows attaching Chrome DevTools to Node.js instances for debugging and profiling. It uses the Chrome DevTools Protocol.

V8 Inspector can be enabled by passing the —inspect flag when starting a Node.js application. It is also possible to supply a custom port with that flag, e.g. —inspect=9222 will accept DevTools connections on port 9222.

To break on the first line of the application code, pass the —inspect-brk flag instead of —inspect .

(In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29 at the end of the URL is generated on the fly, it varies in different debugging sessions.)

If the Chrome browser is older than 66.0.3345.0, use inspector.html instead of js_app.html in the above URL.

Chrome DevTools doesn’t support debugging worker threads yet. ndb can be used to debug them.

Debugging Guide

This guide will help you get started debugging your Node.js apps and scripts.

Читайте также:  View windows crash log

Enable Inspector

When started with the —inspect switch, a Node.js process listens for a debugging client. By default, it will listen at host and port 127.0.0.1:9229. Each process is also assigned a unique UUID.

Inspector clients must know and specify host address, port, and UUID to connect. A full URL will look something like ws://127.0.0.1:9229/0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e .

Node.js will also start listening for debugging messages if it receives a SIGUSR1 signal. ( SIGUSR1 is not available on Windows.) In Node.js 7 and earlier, this activates the legacy Debugger API. In Node.js 8 and later, it will activate the Inspector API.

Security Implications

Since the debugger has full access to the Node.js execution environment, a malicious actor able to connect to this port may be able to execute arbitrary code on behalf of the Node.js process. It is important to understand the security implications of exposing the debugger port on public and private networks.

Exposing the debug port publicly is unsafe

If the debugger is bound to a public IP address, or to 0.0.0.0, any clients that can reach your IP address will be able to connect to the debugger without any restriction and will be able to run arbitrary code.

By default node —inspect binds to 127.0.0.1. You explicitly need to provide a public IP address or 0.0.0.0, etc., if you intend to allow external connections to the debugger. Doing so may expose you to a potentially significant security threat. We suggest you ensure appropriate firewalls and access controls in place to prevent a security exposure.

See the section on ‘Enabling remote debugging scenarios’ on some advice on how to safely allow remote debugger clients to connect.

Local applications have full access to the inspector

Even if you bind the inspector port to 127.0.0.1 (the default), any applications running locally on your machine will have unrestricted access. This is by design to allow local debuggers to be able to attach conveniently.

Browsers, WebSockets and same-origin policy

Websites open in a web-browser can make WebSocket and HTTP requests under the browser security model. An initial HTTP connection is necessary to obtain a unique debugger session id. The same-origin-policy prevents websites from being able to make this HTTP connection. For additional security against DNS rebinding attacks, Node.js verifies that the ‘Host’ headers for the connection either specify an IP address or localhost or localhost6 precisely.

These security policies disallow connecting to a remote debug server by specifying the hostname. You can work-around this restriction by specifying either the IP address or by using ssh tunnels as described below.

Inspector Clients

Several commercial and open source tools can connect to the Node.js Inspector. Basic info on these follows:

node-inspect

  • CLI Debugger supported by the Node.js Foundation which uses the Inspector Protocol.
  • A version is bundled with Node.js and can be used with node inspect myscript.js .
  • The latest version can also be installed independently (e.g. npm install -g node-inspect ) and used with node-inspect myscript.js .

Chrome DevTools 55+, Microsoft Edge

  • Option 1: Open chrome://inspect in a Chromium-based browser or edge://inspect in Edge. Click the Configure button and ensure your target host and port are listed.
  • Option 2: Copy the devtoolsFrontendUrl from the output of /json/list (see above) or the —inspect hint text and paste into Chrome.

Visual Studio Code 1.10+

  • In the Debug panel, click the settings icon to open .vscode/launch.json . Select «Node.js» for initial setup.

Visual Studio 2017

  • Choose «Debug > Start Debugging» from the menu or hit F5.
  • Detailed instructions.

JetBrains WebStorm 2017.1+ and other JetBrains IDEs

  • Create a new Node.js debug configuration and hit Debug. —inspect will be used by default for Node.js 7+. To disable uncheck js.debugger.node.use.inspect in the IDE Registry.

chrome-remote-interface

  • Library to ease connections to Inspector Protocol endpoints.

Gitpod

  • Start a Node.js debug configuration from the Debug view or hit F5 . Detailed instructions

Eclipse IDE with Eclipse Wild Web Developer extension

  • From a .js file, choose «Debug As. > Node program», or
  • Create a Debug Configuration to attach debugger to running Node.js application (already started with —inspect ).

Command-line options

The following table lists the impact of various runtime flags on debugging:

Flag Meaning
—inspect
  • Enable inspector agent
  • Listen on default address and port (127.0.0.1:9229)
—inspect=[host:port]
  • Enable inspector agent
  • Bind to address or hostname host (default: 127.0.0.1)
  • Listen on port port (default: 9229)
—inspect-brk
  • Enable inspector agent
  • Listen on default address and port (127.0.0.1:9229)
  • Break before user code starts
—inspect-brk=[host:port]
  • Enable inspector agent
  • Bind to address or hostname host (default: 127.0.0.1)
  • Listen on port port (default: 9229)
  • Break before user code starts
node inspect script.js
  • Spawn child process to run user’s script under —inspect flag; and use main process to run CLI debugger.
node inspect —port=xxxx script.js
  • Spawn child process to run user’s script under —inspect flag; and use main process to run CLI debugger.
  • Listen on port port (default: 9229)
Читайте также:  Owncloud ������ ��� linux

Enabling remote debugging scenarios

We recommend that you never have the debugger listen on a public IP address. If you need to allow remote debugging connections we recommend the use of ssh tunnels instead. We provide the following example for illustrative purposes only. Please understand the security risk of allowing remote access to a privileged service before proceeding.

Let’s say you are running Node.js on a remote machine, remote.example.com, that you want to be able to debug. On that machine, you should start the node process with the inspector listening only to localhost (the default).

Now, on your local machine from where you want to initiate a debug client connection, you can setup an ssh tunnel:

This starts a ssh tunnel session where a connection to port 9221 on your local machine will be forwarded to port 9229 on remote.example.com. You can now attach a debugger such as Chrome DevTools or Visual Studio Code to localhost:9221, which should be able to debug as if the Node.js application was running locally.

Legacy Debugger

The legacy debugger has been deprecated as of Node.js 7.7.0. Please use —inspect and Inspector instead.

When started with the —debug or —debug-brk switches in version 7 and earlier, Node.js listens for debugging commands defined by the discontinued V8 Debugging Protocol on a TCP port, by default 5858 . Any debugger client which speaks this protocol can connect to and debug the running process; a couple popular ones are listed below.

The V8 Debugging Protocol is no longer maintained or documented.

Built-in Debugger

Start node debug script_name.js to start your script under the builtin command-line debugger. Your script starts in another Node.js process started with the —debug-brk option, and the initial Node.js process runs the _debugger.js script and connects to your target.

node-inspector

Debug your Node.js app with Chrome DevTools by using an intermediary process which translates the Inspector Protocol used in Chromium to the V8 Debugger protocol used in Node.js.

В© OpenJS Foundation. All Rights Reserved. Portions of this site originally В© Joyent.

Руководство по отладке

Это руководство поможет вам начать отладку ваших приложений и скриптов Node.js.

Активация инспектора

При запуске с аргументом —inspect процесс Node.js прослушивает клиент отладки. По умолчанию клиент прослушивается на хосте 127.0.0.1 с портом 9229. Каждому процессу также назначается уникальный UUID.

Клиенты инспектора должны знать и указывать адрес хоста, порт и UUID для подключения. Полный URL будет выглядеть примерно так: ws://127.0.0.1:9229/0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e .

Процесс Node.js также начнет прослушивать сообщения отладки, если он получит сигнал SIGUSR1 . ( SIGUSR1 не доступен в среде Windows.) В Node.js версии 7 и ниже это активирует устаревший Debugger API. В Node.js версии 8 и выше будет активирован Inspector API.

Последствия для безопасности

Так как дебаггер имеет полный доступ к среде выполнения Node.js, злоумышленник, способный подключиться к этому порту, сможет выполнить произвольный код от имени процесса Node. Поэтому важно понимать последствия для безопасности при обличении порта отладчика в публичных и частных сетях.

Публичное обличение порта отладки небезопасно

Если отладчик привязан к какому-либо публичному IP-адресу, или к 0.0.0.0, любой клиент, способный достичь вашего IP-адреса сможет подключиться к отладчику без каких-либо ограничений и сможет запускать произвольный код.

По умолчанию node —inspect привязывается к 127.0.0.1. Чтобы разрешить внешние подключения, вы должны явно предоставить общедоступный IP-адрес или 0.0.0.0 и т.д. Однако это может подвергнуть приложение потенциально значительной угрозе его безопасности. Мы предлагаем вам обеспечить наличие файрволов и других соответствующих средств контроля доступа для того, чтобы предотвратить такую угрозу.

См. раздел ‘Включение сценариев удаленной отладки’, который включает рекомендации о том, как безопасно подключить удаленные клиенты отладчика.

Локальные приложения имеют полный доступ к инспектору

Даже если вы привязали порт инспектора к 127.0.0.1 (по умолчанию), любые приложения, запущенные локально на вашем компьютере, будут иметь неограниченный доступ. Это сделано для того, чтобы локальные отладчики могли легко подключаться.

Браузеры, WebSockets, same-origin policy

Веб-сайты, открытые в веб-браузере, могут отправлять запросы WebSocket и HTTP в соответствии с моделью безопасности браузера. Начальное HTTP-соединение необходимо для получения уникального идентификатора сеанса отладчика. Правило ограничения домена (Same Origin Policy) не позволяет веб-сайтам устанавливать это HTTP-соединение. Для дополнительной защиты от атак DNS rebinding Node.js проверяет, что заголовки ‘Host’ для соединения точно указывают IP-адрес, localhost или localhost6.

Читайте также:  Как сменить язык экранной клавиатуры windows 10

Эти политики безопасности запрещают подключение к удаленному серверу отладки c указанием имени хоста. Вы можете обойти это ограничение, указав либо IP-адрес, либо используя ssh-туннели, как описано ниже.

Клиенты инспектора

Несколько коммерческих и открытых инструментов могут подключаться к инспектору Node.js. Основная информация по ним:

node-inspect

  • Отладчик CLI, поддерживаемый Фондом Node.js, который использует Протокол Инспектора.
  • Соответствующая версия собирается вместе с Node.js, можно использовать с помощью команды node inspect myscript.js .
  • Последняя версия также может быть установлена независимо (например, npm install -g node-inspect ) и использоваться через node-inspect myscript.js .

Инструменты разработчика Chrome 55+, Microsoft Edge

  • Вариант 1: Откройте chrome://inspect в браузере на основе Chromium или edge://inspect в браузере Edge. Нажмите кнопку Configure и убедитесь, что нужные вам хост и порт перечислены в списке.
  • Вариант 2: Скопируйте значение devtoolsFrontendUrl из вывода /json/list ( curl http://localhost:9229/json/list ) или текст подсказки —inspect и откройте его в Chrome.

Visual Studio Code 1.10+

  • На панели «Отладка» (Debug) щелкните значок настроек, чтобы открыть файл .vscode/launch.json . Выберите «Node.js» для первоначальной настройки.

Visual Studio 2017

  • В меню выберите «Debug > Start Debugging» или нажмите F5 .
  • Детальные инструкции.

JetBrains WebStorm 2017.1+ и другие IDE JetBrains

  • Создайте новую конфигурацию отладки Node.js и нажмите кнопку «Debug» ( Shift+F9 ). —inspect будет использоваться по умолчанию для Node.js 7+. Чтобы отключить, снимите флажок js.debugger.node.use.inspect в реестре IDE.

chrome-remote-interface

  • Библиотека для облегчения подключения к эндпоинтам Протокола Инспектора.

Gitpod

  • Запустите конфигурацию отладки Node.js из представления Debug или нажмите F5 . Детальные инструкции

Eclipse IDE c расширением Eclipse Wild Web Developer

  • Открыв файл .js, выберите «Debug As. > Node program», или
  • Создайте конфигурацию отладки, чтобы присоединить отладчик к запущенному приложению Node (уже запущенному с —inspect ).

Аргументы командной строки

В следующей таблице перечислено влияние различных runtime флагов при отладке:

Флаг Значение
—inspect
  • Включить инспектор
  • Прослушивать адрес и порт по умолчанию (127.0.0.1:9229)
—inspect=[host:port]
  • Включить инспектор
  • Прослушивать адрес host (по умолчанию: 127.0.0.1)
  • Прослушивать порт port (по умолчанию: 9229)
—inspect-brk
  • Включить инспектор
  • Прослушивать адрес и порт по умолчанию (127.0.0.1:9229)
  • Прервать выполнение сценария перед началом выполнения пользовательского кода
—inspect-brk=[host:port]
  • Включить инспектор
  • Прослушивать адрес host (по умолчанию: 127.0.0.1)
  • Прослушивать порт port (по умолчанию: 9229)
  • Прервать выполнение сценария перед началом выполнения пользовательского кода
node inspect script.js
  • Запустить дочерний процесс для выполнения пользовательского скрипта под флагом —inspect; использовать основной процесс для запуска отладчика CLI.
node inspect —port=xxxx script.js
  • Запустить дочерний процесс для выполнения пользовательского скрипта под флагом —inspect; использовать основной процесс для запуска отладчика CLI.
  • Прослушивать порт port (по умолчанию: 9229)

Включение сценариев удаленной отладки

Мы рекомендуем, чтобы отладчик никогда не прослушивал общедоступный IP-адрес. Если вам необходимо разрешить удаленные подключения для отладки, мы рекомендуем использовать SSH-тунелли. Следующий пример предоставляется только в целях иллюстрации возможностей. Вы должны понимать все риски информационной безопасности, связанные с предоставлением удаленного доступа к привилегированной службе.

Допустим вы запускаете на удаленной машине, remote.example.com, приложение Node, которое вы хотите отлаживать. На этой машине следует запустить процесс Node с инспектором, прослушивающим только localhost (по умолчанию).

Теперь вы можете настроить ssh-туннель на локальном компьютере, с которого вы хотите инициировать подключение клиента отладки.

Это запустит сессию ssh, в которой соединение с портом 9221 на вашем локальном компьютере будет перенаправлено к порту 9229 на remote.example.com. Теперь вы можете подключить к localhost:9221 отладчик, такой как Chrome DevTools или Visual Studio Code, у которого будет возможность отладки так, как если бы приложение Node.js работало локально.

Устаревший Debugger

Debugger API устарело начиная с Node.js версии 7.7.0. Вместо него следует использовать Inspector API с флагом —inspect.

При запуске с флагом —debug или —debug-brk в версии 7 или ниже, Node.js прослушивает команды отладки, определенные протоколом отладки V8, на порту TCP (по умолчанию 5858 ). Любой клиент отладки, который понимает этот протокол, может подключиться и отладить работающий процесс; пара популярных клиентов перечислены ниже.

Протокол отладки V8 более не поддерживается и не документируется.

Встроенный отладчик

Введите node debug script_name.js для запуска скрипта со встроенным CLI отладчиком. Сам скрипт будет запущен с флагом —debug-brk в другом процессе Node, а первоначальный процесс Node запускает скрипт _debugger.js и подключается к целевому скрипту.

node-inspector

Отлаживайте приложение Node.js с помощью Chrome DevTools используя промежуточный процесс, который переводит протокол инспектора, используемый в Chromium, в протокол отладчика V8, используемый в Node.js.

В© OpenJS Foundation. All Rights Reserved. Portions of this site originally В© Joyent.

Оцените статью