Este es un práctico tutorial de cómo depurar tus aplicaciones hechas en Node.js. Con esto aprenderás a hacer esta tarea por completo y de la mejor manera. Esta guía lo ayudará a comenzar a depurar tus aplicaciones y scripts Node.js. Continúa leyendo y entérate de mas.
Enable an inspector
When started with the switch --inspect
, a Node.js process listens through WebSockets for diagnostic commands defined by the Inspector protocol by default on the host and port 127.0.0.1:9229. Each process is also assigned a unique UUID (for example 0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e).
Los clientes de Inspector deben conocer y especificar la dirección de host, el puerto y el UUID para conectarse a la interfaz de WebSocket. La Url complete ws://127.0.0.1:9229/0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e it depends of course on the actual host and port and on the correct UUID for the instance.
El Inspector también incluye un punto final HTTP para servir metadata sobre el depurador, incluida su URL de WebSocket, UUID y la URL de Chrome DevTools. Obtén estos metadatos enviando una solicitud HTTP a http: // [host: port] / json / list. This returns a JSON object like the following; use the webSocketDebuggerUrl property as the URL to connect directly to the Inspector.
{"description": "node.js instance", "devtoolsFrontendUrl": "chrome-devtools: //devtools/bundled/inspector.html? experiments = true & v8only = true & ws = 127.0.0.1: 9229 / 0f2c936f-b1cd-4ac9-aab3 -f63b0f33d55e "," faviconUrl ":" https://nodejs.org/static/favicon.ico "," id ":" 0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e "," title ":" node "," type ":" node "," url ":" file: // "," webSocketDebuggerUrl ":" ws: //127.0.0.1: 9229 / 0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e "}
You can also instruct a started Node.js process without –inspect to start listening to debug messages by signaling it with SIGUSR1 (en Linux y OS X). A partir del Node 7, esto activa la API de depuración heredada; en el Node 8 y posterior activará la API Inspector.
Security is involved
Since the debugger has full access to the Node.js runtime, a malicious actor capable of connecting to this port can execute arbitrary code on behalf of the node process. It is important to understand the security implications of exposing the debug port on public and private networks.
Exposing the debug port publicly is not safe
Si el depurador está vinculado a una IP adress pública, o 0.0.0.0, any client que pueda acceder a su dirección IP podrá conectarse al depurador sin ninguna restricción y podrá ejecutar código arbitrario.
By default node –inspect is bound to 127.0.0.1. You must explicitly provide a public IP address or 0.0.0.0, etc., if you want to allow external connections to the debugger. Doing so can expose you to a potentially significant security threat. We suggest that you secure proper firewalls and access controls to avoid a security exposure.
Local applications have full access to the inspector.
Even if you bind the inspector port to 127.0.0.1 (the default), any application running locally on your PC will have unrestricted access. This is by design to allow local debuggers to conveniently attach.
Browsers, websockets y política del mismo origen.
Los sitios Web abiertos en un browser web pueden hacer solicitudes WebSocket y HTTP bajo el modelo de seguridad del navegador. Es necesaria una conexión HTTP inicial para obtener un Id de sesión de depurador único. La misma política de origen impide que los sitios web puedan realizar esta conexión HTTP.
Para mayor seguridad contra los ataques de reencuadernación de DNS, Node.js verifica que las cabeceras del ‘Host’ para la conexión especifiquen una dirección IP o localhost o localhost6 con precisión.
Estas políticas de seguridad no permiten conectarse a un server de depuración remoto especificando el nombre del host. Puedes evitar esta restricción especificando la dirección IP o utilizando túneles ssh como se describe a continuación.
Inspector Clients
Varias herramientas comerciales y de Open Source pueden conectarse al Inspector de nodos. A continuación se ofrece información básica sobre estos temas:
- node-inspect
- CLI debugger supported by the Node.js Foundation that uses the Inspector Protocol.
- One version is included with Node and can be used with the inspect myscript.js node.
- The latest version can also be installed standalone (for example, npm install -g node-inspect) and used with node-inspect myscript.js.
- Chrome DevTools 55+
- Option 1: Open chrome: // inspect in a Chromium-based browser. Click the Configure button and make sure the destination host and port are listed.
- Option 2: Copy devtoolsFrontendUrl from the output of / json / list (see above) or the –inspect hint text and paste it into Chrome.
- Opción 3: Instale Chrome Extension NIM (Administrador del Inspector de Nodos): https://chrome.google.com/webstore/detail/nim-node-inspector-manage/gnhhdgbaldcilmgcpfddgdbkhjohddkj
- Visual Studio Code 1.10+
- In the debugging panel, click the settings icon to open .vscode / launch.json. Select "Node.js" for initial configuration.
- Visual Studio 2017
- Choose "Debug> Start Debugging" from the menu or press F5.
- JetBrains WebStorm 2017.1+ and other JetBrains IDEs
- Create a new Node.js debug configuration and click Debug. –Inspect will be used by default for Node.js 7+. To disable js.debugger.node.use.inspect in the IDE Registry.
- Chrome remote interface
- Has a library to facilitate connections to Inspector protocol endpoints
Command line options
The following table lists the impact of various runtime flags on debugging:
- –Inspect:
- Enable inspection agent
- Listen on the default address and port (127.0.0.0.1: 9229)
- –Inspect = [host: port]:
- Enable inspection agent
- Bind to hostname address or host (default: 127.0.0.0.1)
- Listen on port (default: 9229)
- –Inspect-brk
- Enable inspection agent
- Listen on the default address and port (127.0.0.1:9229)
- Pausa antes de que comience el código de Username
- –Inspect-brk =[host: port]
- Enable inspection agent
- Bind to hostname address or host (default: 127.0.0.0.1)
- Listen on port (default: 9229)
- Pause before user code starts
- node inspect script.js
- Spawn child process to run user script under –inspect flag; and use the main process to run the CLI debugger.
- node inspect –port = xxxx script.js
- Spawn child process to run user script under –inspect flag; and use the main process to run the CLI debugger.
- Listen on port (default: 9229)
Enabling remote debugging scenarios
I recommend that you never make the debugger listen on a public IP address. If you need to allow remote debugging connections, I recommend using ssh tunnels instead. I am providing the following example for illustrative purposes only. Please understand the security risk of allowing remote access to a privileged service before proceeding.
Suppose you are running Node.js on a remote machine, remote.example.com, 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).
$ node --inspect server.js [php] Now, on your local machine from where you want to start a debug client connection, you can configure an ssh tunnel: [php] $ ssh -L 9221: localhost: 9229 @ user_sample. remote.com
This starts an ssh tunnel session where a connection to port 9221 of your local machine will be forwarded to port 9229 of remote.example.com. Now you can attach a debugger like Chrome DevTools or Visual Studio Code to localhost: 9221, which should be able to debug as if the Node.js application was running locally.