Replies: 2 comments
-
You can debug using Visual Studio Code or WebStorm. Node.js debugging in VS CodeThe Visual Studio Code editor has built-in debugging support for the Node.js runtime and can debug JavaScript, TypeScript, and many other languages that are transpiled into JavaScript. Setting up a project for Node.js debugging is straightforward with VS Code providing appropriate launch configuration defaults and snippets. There are a few ways you can debug your Node.js programs in VS Code:
Auto AttachIf the Auto Attach feature is enabled, the Node debugger automatically attaches to certain Node.js processes that have been launched from VS Code's Integrated Terminal. To enable the feature, either use the Toggle Auto Attach command from the Command Palette ( There are three modes for auto attach, which you can select in the resulting Quick Pick and via the debug.javascript.autoAttachFilter setting:
After enabling Auto Attach, you'll need to restart your terminal. This can be done by clicking the ⚠ icon in the top right of the terminal, or just creating a new one. Then, the debugger should attach to your program within a second: When auto attach is on, the Additional ConfigurationOther Launch Configuration Properties You can apply other properties normally found in launch.json to auto attach in the debug.javascript.terminalOptions setting. For example, to add node internals to your skipFiles, you could add the following to your user or workspace settings: "debug.javascript.terminalOptions": {
"skipFiles": [
"<node_internals>/**"
]
}, Auto Attach Smart Patterns In [
"!**/node_modules/**", // exclude scripts in node_modules folders
"**/$KNOWN_TOOLS$/**" // but include some common tools
]
[
"!**/node_modules/**",
"**/$KNOWN_TOOLS$/**",
"!**/node_modules/mocha/**", // use "!" to exclude all scripts in "mocha" node modules
"**/node_modules/my-cool-test-runner/**" // include scripts in the custom test runner
] JavaScript Debug TerminalIn a similar way to auto attach, the JavaScript Debug Terminal will automatically debug any Node.js process you run in it. You can create a Debug Terminal by running the Debug: Create JavaScript Debug Terminal command from the Command Palette ( Additional ConfigurationOther Launch Configuration Properties You can apply other properties normally found in launch.json to the debug terminal in the debug.javascript.terminalOptions setting. For example, to add node internals to your skipFiles, you could add the following to your user or workspace settings: "debug.javascript.terminalOptions": {
"skipFiles": [
"<node_internals>/**"
]
}, Launch ConfigurationLaunch configs are the traditional way to set up debugging in VS Code, and provide you the most configuration options for running complex applications. In this section we'll go into more detail about configurations and features for more advanced debugging scenarios. You'll find instruction for debugging with source maps, stepping over external code, doing remote debugging, and much more. If you'd like to watch an introductory video, see Getting started with Node.js debugging.
Launch configuration attributesDebugging configurations are stored in a Below is a reference of common The following attributes are supported in launch configurations of type
These attributes are only available for launch configurations of request type
This attribute is only available for launch configurations of request type
Launch configurations for common scenariosYou can trigger IntelliSense ( You can also bring up the snippets with the Add Configuration... button in the lower right of the These are the available snippets:
Node consoleBy default, Node.js debug sessions launch the target in the internal VS Code Debug Console. Since the Debug Console does not support programs that need to read input from the console, you can enable either an external terminal or use the VS Code Integrated Terminal by setting the If an external terminal is used, you can configure which terminal program to use via the Launch configuration support for 'npm' and other toolsInstead of launching the Node.js program directly with node, you can use 'npm' scripts or other task runner tools directly from a launch configuration:
Let's look at an 'npm' example. If your "scripts": {
"debug": "node myProgram.js"
}, the corresponding launch configuration would look like this: {
"name": "Launch via npm",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script", "debug"
],
} Multi version supportIf you are using 'nvm' (or 'nvm-windows') to manage your Node.js versions, it is possible to specify a {
"type": "node",
"request": "launch",
"name": "Launch test",
"runtimeVersion": "14",
"program": "${workspaceFolder}/test.js"
} If you are using 'nvs' to manage your Node.js versions, it is possible to use {
"type": "node",
"request": "launch",
"name": "Launch test",
"runtimeVersion": "chackracore/8.9.4/x64",
"program": "${workspaceFolder}/test.js"
} Make sure to have those Node.js versions installed that you want to use with the If you omit the minor and patch version and have, for example, Load environment variables from external fileThe VS Code Node debugger supports loading environment variables from a file and passing them to the Node.js runtime. To use this feature, add an attribute //...
"envFile": "${workspaceFolder}/.env",
"env": { "USER": "john doe" }
//... Any environment variable specified in the Here's an example of an
Attaching to Node.jsIf you want to attach the VS Code debugger to an external Node.js program, launch Node.js as follows: node --inspect program.js or if the program shouldn't start running, but must wait for the debugger to attach: node --inspect-brk program.js Now you have a couple options for attaching the debugger to your program:
Let's go through these options in detail: Attach to Node Process actionThe Attach to Node Process command from the Command Palette ( The individual processes listed in the picker show the debug port and process ID. Once you select your Node.js process in that list, the Node.js debugger will try to attach to it. In addition to Node.js processes, the picker also shows other programs that were launched with one of the various forms Setting up an "Attach" configurationThis option requires more work but in contrast to the previous two options it allows you to configure various debug configuration options explicitly. The simplest "attach" configuration looks like this: {
"name": "Attach to Process",
"type": "node",
"request": "attach",
"port": 9229
} The port If you want to attach to a Node.js process that hasn't been started in debug mode, you can do this by specifying the process ID of the Node.js process as a string: {
"name": "Attach to Process",
"type": "node",
"request": "attach",
"processId": "53426"
} Since it is a bit laborious to repeatedly find the process ID and enter it in the launch configuration, Node debug supports a command variable Using the {
"name": "Attach to Process",
"type": "node",
"request": "attach",
"processId": "${command:PickProcess}"
} Stop debuggingUsing the Debug: Stop action (available in the Debug toolbar or via the Command Palette) stops the debug session. If the debug session was started in "attach" mode (and the red terminate button in the Debug toolbar shows a superimposed "plug"), pressing Stop disconnects the Node.js debugger from the debuggee that then continues execution. If the debug session is in "launch" mode, pressing Stop does the following:
So if you see that a debug session doesn't end when you press the red Stop button, then press the button again to force a shutdown of the debuggee. Note that on the Windows operating system, pressing Stop always forcibly kills the debuggee and its child processes. Source mapsThe JavaScript debugger of VS Code supports source maps that help debugging of transpiled languages, for example, TypeScript or minified/uglified JavaScript. With source maps, it's possible to single step through or set breakpoints in the original source. If no source map exists for the original source, or if the source map is broken and cannot successfully map between the source and the generated JavaScript, then breakpoints show up as unverified (gray hollow circles). The source map feature is controlled by the Tool ConfigurationSince source maps are not always automatically created, you should make sure to configure your transpiler to create them. For example: TypeScript For TypeScript, you can enable sourcemaps by passing tsc --sourceMap --outDir bin app.ts Babel For Babel, you'll want to set the sourceMaps option to npx babel script.js --out-file script-compiled.js --source-maps Webpack Webpack has numerous source map options. We recommend setting the property Also, if you have additional compilation steps in webpack, such as using a TypeScript loader, you'll also want to make sure that those steps are set up to generate sourcemaps. Otherwise, the sourcemaps that webpack generates will map back to the compiled code from the loader, instead of the real sources. Source Map DiscoveryBy default, VS Code will search your entire workspace, excluding {
"version": "0.2.0",
"configurations": [
{
"name": "Launch TypeScript",
"type": "node",
"request": "launch",
"program": "app.ts",
"outFiles": [ "${workspaceFolder}/bin/**/*.js" ]
}
]
} Note that the Source Map ResolutionBy default, only source maps in your You can configure this behavior by setting the "resolveSourceMapLocations": [
"out/**/*.js",
"node_modules/some-dependency/**/*.js",
] Smart steppingWith the Smart stepping is especially useful for cases like async/await downcompilation in TypeScript, where the compiler injects helper code that is not covered by a source map. The JavaScript source map tipsA common issue when debugging with source maps is that you'll set a breakpoint, and it will turn gray. If you hover the cursor over it, you'll see the message, When you set a breakpoint in When you build your Finally, the debug adapter searches for the full path of Here are some things to try when your breakpoints turn gray:
Remote debugging
The Node.js debugger supports remote debugging where you attach to a process running on a different machine, or in a container. Specify a remote host via the {
"type": "node",
"request": "attach",
"name": "Attach to remote",
"address": "192.168.148.2", // <- remote address here
"port": 9229
} By default, VS Code will stream the debugged source from the remote Node.js folder to the local VS Code and show it in a read-only editor. You can step through this code, but cannot modify it. If you want VS Code to open the editable source from your workspace instead, you can set up a mapping between the remote and local locations. A {
"type": "node",
"request": "attach",
"name": "Attach to remote",
"address": "TCP/IP address of process to be debugged",
"port": 9229,
"localRoot": "${workspaceFolder}",
"remoteRoot": "C:\\Users\\username\\project\\server"
} Access Loaded ScriptsIf you need to set a breakpoint in a script that is not part of your workspace and therefore cannot be easily located and opened through normal VS Code file browsing, you can access the loaded scripts via the LOADED SCRIPTS view in the Run and Debug view: The LOADED SCRIPTS view lets you quickly select the script by typing its name or filter the list when Enable Filter on Type is on. Scripts are loaded into a read-only editor where you can set breakpoints. These breakpoints are remembered across debug sessions but you only have access to the script content while a debug session is running. Restarting debug sessions automatically when source is editedThe If you have started your program nodemon --inspect server.js you can attach the VS Code debugger to it with the following launch configuration: {
"name": "Attach to node",
"type": "node",
"request": "attach",
"restart": true,
"port": 9229
} Alternatively you can start your program {
"name": "Launch server.js via nodemon",
"type": "node",
"request": "launch",
"runtimeExecutable": "nodemon",
"program": "${workspaceFolder}/server.js",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
Restart frameThe Node debugger supports restarting execution at a stack frame. This can be useful in situations where you have found a problem in your source code and you want to rerun a small portion of the code with modified input values. Stopping and then restarting the full debug session can be time-consuming. The Restart Frame action allows you to reenter the current function after you have changed variables with the Set Value action: Restart Frame won't roll back mutation to state outside of the function, so it may not always work as expected. BreakpointsConditional BreakpointsConditional breakpoints are breakpoints that only pause when an expression returns a truthy value. You can create one by right-clicking in the gutter beside a line number and selecting "Conditional Breakpoint": LogpointsSometimes you want to just log a message or value when code hits a certain location, rather than pausing. You can do this with logpoints. Logpoints don't pause, but rather log a message to the Debug Console when hit. In the JavaScript debugger, you can use curly braces to interpolate expressions into the message, like You can create one by right-clicking in the gutter beside a line number and selecting "Logpoint". For example, this might log something like Hit count breakpointsThe 'hit count condition' controls how many times a breakpoint needs to be hit before it will 'break' execution. You can place a hit count breakpoint by right-clicking in the gutter beside a line number, selecting "Conditional Breakpoint", and then switching to "Hit Count". The hit count syntax supported by the Node.js debugger is either an integer or one of the operators Some examples:
Breakpoint validationFor performance reasons, Node.js parses the functions inside JavaScript files lazily on first access. As a consequence, breakpoints don't work in source code areas that haven't been seen (parsed) by Node.js. Since this behavior is not ideal for debugging, VS Code passes the Since the When doing so, you will find that some of your breakpoints don't "stick" to the line requested but instead "jump" for the next possible line in already-parsed code. To avoid confusion, VS Code always shows breakpoints at the location where Node.js thinks the breakpoint is. In the BREAKPOINTS section, these breakpoints are shown with an arrow between requested and actual line number: This breakpoint validation occurs when a session starts and the breakpoints are registered with Node.js, or when a session is already running and a new breakpoint is set. In this case, the breakpoint may "jump" to a different location. After Node.js has parsed all the code (for example, by running through it), breakpoints can be easily reapplied to the requested locations with the Reapply button in the BREAKPOINTS section header. This should make the breakpoints "jump back" to the requested location. Skipping uninteresting codeVS Code Node.js debugging has a feature to avoid source code that you don't want to step through (also known as 'Just My Code'). This feature can be enabled with the For example, using: "skipFiles": [
"${workspaceFolder}/node_modules/**/*.js",
"${workspaceFolder}/lib/**/*.js"
] all code in the Built-in core modules of Node.js can be referred to by the 'magic name' "skipFiles": [
"<node_internals>/**/*.js"
] The exact 'skipping' rules are as follows:
Skipped source is shown in a 'dimmed' style in the CALL STACK view: Hovering over the dimmed entries explains why the stack frame is dimmed. A context menu item on the call stack, Toggle skipping this file enables you to easily skip a file at runtime without adding it to your launch config. This option only persists for the current debugging session. You can also use it to stop skipping a file that is skipped by the
"skipFiles": [
"${workspaceFolder}/node_modules/**/*.js",
"!${workspaceFolder}/node_modules/math/**/*.js"
]
Supported Node-like runtimesThe current VS Code JavaScript debugger supports Node version at or above 8.x, recent Chrome versions, and recent Edge versions (via the Next stepsIn case you didn't already read the Node.js section, take a look at:
To see tutorials on the basics of Node.js debugging, check out these videos:
To learn about VS Code's task running support, go to:
To write your own debugger extension, visit:
Common questionsCan I debug if I'm using symlinks?Yes, if you've created symlinks for folders inside your project, such as with {
"runtimeArgs": [
"--preserve-symlinks"
]
} If your main script is inside a symlinked path, then you will also need to add the How do I debug ECMAScript modules?If you use esm or pass
Running and debugging Node.jsWebStorm helps you run and debug your Node.js applications. You can debug applications that are started from WebStorm as well as attach to already running applications. Before you start Running a Node.js application Create a Node.js run/debug configuration Open the Edit Configurations dialog Specify the Node.js interpreter to use. If you choose the Project alias, WebStorm will automatically use the project default interpreter from the Node interpreter field on the Node.js page . In most cases, WebStorm detects the project default interpreter and fills in the field itself. You can also choose another configured local or remote interpreter or click the Browse button and configure a new one. See Configuring remote Node.js interpreters, Configuring a local Node.js interpreter, and Using Node.js on Windows Subsystem for Linux for details. In the JavaScript File field, specify the path to the main file of the application that starts it (for example, bin/www for Express applications). Optionally: Specify the Node parameters that customize the start of Node.js. For example, you may want to enable an experimental Node.js feature or pass another option, see the Node.js official website for details. In the Application parameters field, specify the Node.js-specific arguments to be passed to the application on start through the process.argv array. To open the application in the browser automatically, configure a before-launch task. Click App general arrow right to expand the Before launch area, click the Add button, and select Launch Web Browser from the list. In the dialog that opens, specify the URL of the application starting page, for example, localhost:3000 for Express applications, and the browser to use. Run an application Start an app with a run/debug configuration If you are using a logging tool like morgan in your application and this tool writes logs to a file, you can see these logs in the Console tab of the Run tool window. Manage logs when running a Node.js application Click the Add button next to the Log files to be shown in console field which lists the available log files (if any). In the Edit Log Files Aliases dialog that opens, type the alias name to show in the list of log entries and specify the location of the log file. Select whether you want to show all files that this pattern covers or only the last one. Click OK to return to Node.js Run/Debug Configuration dialog, where the new log file is added to the list. Select the Is Active checkbox next to it. To skip the previous content, select the Skip Content checkbox. Optionally: To enable saving the Process Console output to a log file, select the Save console output to file checkbox and specify the file location. Choose when you want the Process Console shown. Debugging a Node.js application You can initiate a debugging session in two ways: Start the debugger together with your application using a Node.js run/debug configuration. Attach the debugger to an already running application. In this case, your application is already running in the debug mode and WebStorm attaches to a running process. WebStorm recognizes --inspect, --inspect-brk, and now deprecated --debug flags so you can make any application accessible for debugging. To debug a running application, use an Attach to Node.js/Chrome configuration. With WebStorm, you can also debug Node.js applications that are running in Vagrant boxes, in Docker containers, or on remote hosts accessible via various transfer protocols or via SSH. Starting the debugger together with a Node.js application on your computer Create a Node.js run/debug configuration as described above. To open the application in the browser automatically, configure a before-launch task. Click App general arrow right to expand the Before launch area, click the Add button, and select Launch Web Browser from the list. In the dialog that opens, specify the URL of the application starting page, for example, localhost:3000 for Express applications, and the browser to use. If necessary, WebStorm can generate a JavaScript Debug configuration and start it automatically together with the Node.js configuration as described in Debugging the server- and the client-side code. Select the newly created Node.js configuration from the Select run/debug configuration list on the toolbar and click the Debug button (the Debug button) next to the list. Start a Node.js debugging session with a run/debug configuration Perform the steps that will trigger the execution of the code with the breakpoints. For example, navigate from the starting page of your application to another page in the browser. Switch to WebStorm, where the controls of the Debug tool window are now enabled. Proceed with the debugging session — step through the breakpoints, switch between frames, change values on-the-fly, examine a suspended program, evaluate expressions, and set watches. Debugging a running Node.js application In either case, a debugging session is initiated through an Attach to Node.js/Chrome configuration. Start the debugger from the built-in Terminal or from the Run or Debug tool window https://resources.jetbrains.com/help/img/idea/2022.3/ws_node_debug_attach_from_terminal_dark.png Open the embedded Terminal (Alt+F12) and, type: node --inspect-brk Launch a script from package.json or from the npm tool window, see Run and debug scripts for details. Launch an app in the debug mode: launch a script The Terminal, the Run tool window, or the Console tab of the Debug tool window shows an information message Debugger listening :, the default port is 9229. To start debugging, hold Ctrl+Shift and click the link. WebStorm starts a debugging session with an automatically generated Attach to Node.js/Chrome configuration. Alternatively, copy the port number from the Debugger listening : message and paste it later in the Attach to Node.js/Chrome configuration. Debug with Chrome Debugging Protocol Set the breakpoints as necessary. Select Run | Edit Configurations from the main menu, then click Add New Configuration in the Edit Configuration dialog that opens, and select Attach to Node.js/Chrome from the list. The Run/Debug Configuration: Attach to Node.js/Chrome dialog opens. Specify the host where the target application is running and the port passed to --inspect or --inspect-brk when starting the Node.js process to connect to. Copy the port number from the information message Debugger listening : in the Terminal tool window or in the Run tool window that controls the running application. Start debugging from Run tool window or Terminal: information message Optionally: specify the remote paths for the project folders in the Remote URLs of local files area. This is helpful if the root folder of the running application is different from the name of you WebStorm project root folder. In the Attach to area, select Chrome or Node.js > 6.3 started with --inspect. Select the newly created Attach to Node.js/Chrome configuration from the Select run/debug configuration list on the toolbar and click the Debug button (the Debug button) next to the list. The Debug tool window opens. Perform the actions that will trigger the code at the breakpoint. Control over the debugging session returns to WebStorm. Switch to WebStorm. In the Debug tool window, step through the breakpoints, switch between frames, change values on-the-fly, examine a suspended program, evaluate expressions, and set watches. Debug with V8 Debugging Protocol Create an Attach to Node.js/Chrome run/debug configuration as described above and specify the host and the port passed to --debug. The default port is 9229. Make sure the application to debug was launched with the following parameters: --debug=. The default port is 5858. Proceed as during a debugging session with Chrome Debugging Protocol. Debugging a Node.js application that uses nodemon The WebStorm built-in debugger can automatically reconnect to running Node.js processes. This lets you debug Node.js applications that use the nodemon utility, which automatically reloads your Node.js process when the code is updated. To debug such application, you need to start it in the debug mode (with the --inspect or --inspect-brk flag) and then connect to it using the Attach to a Node.js/Chrome debug configuration with the Reconnect Automatically option on. Install nodemon Start an application with nodemon in the debug mode debug": "nodemon --inspect <path_to_the_file_that_starts_your_application> Alternatively, pass the inspect flag through a Node.js run/debug configuration as described above. Debug an application Create a new Attach to a Node.js/Chrome configuration as described in Debugging a running Node.js application and select the Reconnect automatically checkbox. Attach no Node.js run configuration: select the Reconnect automatically checkbox Node.js application with nodemon running in the debug mode: check the port Now, every time you make any changes to the code and save them Ctrl+S, nodemon will automatically reload the application and the debugger will automatically re-attach to the restarted process. |
Beta Was this translation helpful? Give feedback.
-
Please provide specific information, including what you want to do, what you did, and what results you got. |
Beta Was this translation helpful? Give feedback.
-
Describe the problem related to the feature request
How to debug source code
Describe the solution you'd like
How to debug source code
Describe alternatives you've considered
No response
Additional context
No response
Beta Was this translation helpful? Give feedback.
All reactions