VSCode is a powerful editor, especially for debugging. To debug Node.js (ES6) code in VSCode, follow these steps:
1. Ensure Node.js is installed
First, ensure Node.js is installed in your development environment. You can run the following command in the terminal to verify its installation:
bashnode -v
If Node.js is installed, the command will display the current version.
2. Open your Node.js project
Open the folder containing your Node.js code in VSCode. You can do this by selecting "File" > "Open Folder".
3. Create a debug configuration file
Enabling debugging in VSCode is straightforward. First, click the debug icon on the left sidebar (a bug icon), then click the "Create a launch.json file" link at the top of the page. Select the Node.js environment to automatically generate a basic debug configuration file.
This generated launch.json file may appear as follows:
json{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": [ "<node_internals>/**" ], "program": "${workspaceFolder}/app.js" } ] }
In this configuration, the program property specifies the main file to debug, such as app.js.
4. Set breakpoints
Setting breakpoints in your JavaScript code is simple. Open your JavaScript file in the VSCode editor and click the space next to the line number where you want execution to pause. This adds a red dot indicating the breakpoint location.
5. Start debugging
After setting breakpoints, return to the debug view and click the green "Start Debugging" button. The Node.js application will launch and automatically pause when it hits any breakpoint. At this point, you can inspect variable values, call stacks, and execution steps.
6. Use debugging controls
During debugging, utilize the debug toolbar at the top of the screen to step through (execute line by line), step into (enter function internals), step out (exit the current function), and continue execution until the next breakpoint.
By using VSCode for debugging, you can more easily understand code execution flow and logical structure, which is invaluable for development and troubleshooting.
Example
Suppose you are developing a simple HTTP server and want to debug the request handling function. Set a breakpoint at the start of the handler function, then trigger it by sending an actual HTTP request. This allows you to inspect request content and handling logic in real time.
Debugging is an essential part of development, and VSCode provides an intuitive, powerful interface to help developers efficiently debug code.