如何在Visual Studio代码中调试Node.js代码

介绍 (Introduction)

Visual Studio Code has a large amount of functionality built-in, including support for debugging applications. In this article, you will configure VS Code to debug Node.js by downloading the Debugger for Chrome extension, creating a debug configuration, launching a debug configuration, and setting breakpoints.

Visual Studio Code具有大量内置功能,包括对调试应用程序的支持。 在本文中,您将通过下载Debugger for Chrome扩展程序,创建调试配置,启动调试配置以及设置断点来配置VS Code以调试Node.js。

先决条件 (Prerequisites)

To complete this tutorial, you will need:

要完成本教程,您将需要:

For this tutorial, you can apply the lessons to one of your JavaScript projects that can be run on a Node server.

对于本教程,您可以将课程应用于可以在节点服务器上运行的一个JavaScript项目。

There is also the option to follow along using a sample application if you prefer.

如果愿意,还可以选择使用示例应用程序。

第1步-创建示例应用程序(可选) (Step 1 — Creating a Sample App (Optional))

This tutorial will debug an example application called Quick Chat. If you do not have a project to follow along with, you can follow this step to create this application.

本教程将调试一个名为Quick Chat的示例应用程序。 如果您没有要遵循的项目,则可以按照此步骤创建此应用程序。

You use Git to clone the Design-and-Build-a-Chat-Application-with-Socket.io repo. You can also download the zip file and unzip the contents.

您可以使用Git来克隆 Design-and-Build-a-Chat-Application-with-Socket.io存储库 。 您也可以下载zip文件并解压缩内容。

Note: If you need Git installed on your system, consult Getting Started with Git tutorial.

注意:如果您需要在系统上安装Git,请查阅Git入门教程。

For this tutorial, you will use the code from Part 8 of the project. Take a moment to familiarize yourself with how you would expect the application to work.

对于本教程,您将使用项目第8部分中的代码。 花一点时间熟悉一下应用程序的预期工作方式。

Start by navigating to the project directory and then into the part-8 directory:

首先导航到项目目录,然后进入part-8目录:

  • cd Design-and-Build-a-Chat-Application-with-Socket.io

    cd使用socket.io设计和构建聊天应用程序

  • cd part-8

    CD第8部分

Next, install the npm packages for the project:

接下来,为项目安装npm软件包:

  • npm install

    npm安装

Then, start the server:

然后,启动服务器:

  • npm start

    npm开始

If you visit 127.0.0.1:3000 in Chrome, you will see a username prompt. After providing a username and clicking the Chat! button, you will be directed to the chat app and see the following:

如果您在Chrome中访问127.0.0.1:3000 ,则会看到用户名提示。 提供用户名并单击聊天之后! 按钮,您将被定向到聊天应用程序并看到以下内容:

Output
输出量
  • User joined the chat...

    用户加入了聊天...

By entering text in the input at the bottom of the window and clicking the Send button, your messages will display in the chat window.

通过在窗口底部的输入中输入文本并单击“ 发送”按钮,您的消息将显示在聊天窗口中。

If you open a new browser tab and visit the same URL, you can log in as another user and observe chat messages sent to the chat windows in both browser tabs. This behavior is the expected functionality for this application.

如果打开新的浏览器选项卡并访问相同的URL,则可以以其他用户身份登录,并在两个浏览器选项卡中观察发送到聊天窗口的聊天消息。 此行为是此应用程序的预期功能。

第2步-创建断点 (Step 2 — Creating a Breakpoint)

Now, let’s create a breakpoint in our app. Breakpoints allow you to pause your code and inspect it.

现在,让我们在应用程序中创建一个断点。 断点允许您暂停代码并检查代码。

The Quick Chat application is a Node/Express app that uses Socket.io to allow users to chat with each other in real-time. We will add a breakpoint where a client connects to our server.

快速聊天应用程序是一个Node / Express应用程序,它使用Socket.io允许用户彼此实时聊天。 我们将在客户端连接到服务器的地方添加一个断点。

To create a breakpoint in VS Code, click in the gutter, or empty space, to the left of the line numbers.

要在VS Code中创建断点,请在行号左侧的装订线或空白处单击。

As shown in the following screenshot, we’ve created a breakpoint (the red circle) inside the function that gets called each time a user gets connected.

如以下屏幕截图所示,我们在函数内部创建了一个断点(红色圆圈),每次用户连接时都会调用该断点。

part-8/server.js
第8部分/server.js
// ...
io.on('connection', socket => {
  console.log('a user connected');
  // ...
});

Regardless of what application you are debugging, set a breakpoint that can be triggered easily, such as when the application loads, a route is triggered, etc.

无论您要调试哪个应用程序,都应设置一个可以轻松触发的断点,例如在应用程序加载时,触发路由等。

步骤3 —使用VS代码调试面板 (Step 3 — Using the VS Code Debugging Panel)

To open the debug panel, click on the bug icon on the sidebar (on the left side by default). You’ll notice that there are four different sections: variables, watch, call stack, and breakpoints.

要打开调试面板,请单击侧栏上的错误图标(默认情况下为左侧)。 您会注意到有四个不同的部分: 变量监视调用堆栈断点

At the top of the panel, you will see a green play button and a dropdown that says No Configurations if you have yet to create a debug configuration. If you have already created a configuration, you’ll see it listed there.

如果尚未创建调试配置,则在面板顶部,将看到一个绿色的播放按钮和一个下拉菜单,显示“ 配置”。 如果您已经创建了配置,则会在此处列出它。

VS Code stores debug configurations in a file called launch.json inside of a folder called .vscode. VS Code helps us not only create that folder and file but also helps to generate predefined configurations as well. Let’s take a look at creating our first one.

VS Code将调试配置存储在名为launch.json的文件夹内名为.vscode的文件中。 VS Code不仅可以帮助我们创建该文件夹和文件,还可以帮助我们生成预定义的配置。 让我们来看看创建第一个。

To create your initial launch.json file, click the No Configurations dropdown and choose Add Configuration. From here, ignore the popup and we will get started with creating our first configuration.

要创建您的初始launch.json文件,请点击No Configurations下拉菜单,然后选择Add Configuration 。 从这里开始,忽略弹出窗口,我们将开始创建第一个配置。

调试配置的关键组件 (Key Components of a Debug Configuration)

  • name - The name of the configuration as displayed in the configurations dropdown.

    name -如显示在配置下拉的配置的名称。

  • request - The type of action that you want to take.

    request您要执行的操作类型。

  • type - The type of debugger for the configuration. This type can be Node, Chrome, PHP, etc.

    type -为对配置的类型调试器。 此类型可以是Node,Chrome,PHP等。

As you create different configurations, VS Code will also provide IntelliSense for other properties that can be defined.

在创建不同的配置时,VS Code还将为可以定义的其他属性提供IntelliSense

第4步-使用启动程序进行调试 (Step 4 — Debugging with Launch Program)

This first configuration will launch our Node application in debug mode. Running in debug mode means that VS Code will connect to our app over a specific port for debugging. For this configuration, we need to define the program file that will be run. The configuration looks like this:

第一个配置将以调试模式启动我们的Node应用程序。 在调试模式下运行意味着VS Code将通过特定端口连接到我们的应用进行调试。 对于此配置,我们需要定义将要运行的程序文件。 配置如下所示:

.vscode/launch.json
.vscode / launch.json
{
  "type": "node",
  "request": "launch",
  "name": "Launch Program",
  "program": "${workspaceFolder}/app.js"
},

To run this configuration, choose it from the configurations dropdown list, and click the green play button. Your debug action bar will pop up in the top right with step, continue, restart, and stop buttons.

要运行此配置,请从配置下拉列表中选择它,然后单击绿色的播放按钮。 您的调试操作栏将显示在右上角,其中包含stepContinuerestartstop按钮。

To start a Node application in debug mode going forward, use the --inspect flag.

要继续以调试模式启动Node应用程序,请使用--inspect标志。

第5步-使用进程ID附加进行调试 (Step 5 — Debugging with Attach by Process ID)

The second configuration we’ll look at is attaching to a Node process by Process ID. This scenario would be relevant for an application that is already running on your local environment.

我们将要看到的第二个配置是通过Process ID附加到Node进程。 该方案与您的本地环境中已在运行的应用程序有关。

.vscode/launch.json
.vscode / launch.json
{
  "type": "node",
  "request": "attach",
  "name": "Attach by Process ID",
  "processId": "${command:PickProcess}"
},

For this, we will need to start the Node server ourselves before running the debug configuration. Use the following command to start your server (using --inspect as mentioned earlier) and replace app.js with the name of your server file.

为此,我们将需要在运行调试配置之前自行启动节点服务器。 使用以下命令启动服务器(使用--inspect提到的--inspect ),并将app.js替换为服务器文件的名称。

  • node --inspect app.js

    节点-检查app.js

With your server started, now you can run your debug configuration. When prompted, choose the Node process that corresponds to the command you just ran to start the server.

随着服务器启动,现在您可以运行调试配置。 出现提示时,选择与您刚运行的用于启动服务器的命令相对应的Node进程。

You will get a successful connection:

您将获得成功的连接:

步骤6 —调试并附加到端口 (Step 6 — Debugging with Attach to Port)

For our third configuration, we will be attaching to an existing Node application running on a given port.

对于第三个配置,我们将附加到在给定端口上运行的现有Node应用程序。

.vscode/launch.json
.vscode / launch.json
{
  "type": "node",
  "request": "attach",
  "name": "Attach to Port",
  "port": 9229
},

9229 is the default port for debugging when using the --inspect flag, so that’s what we’re going to use.

9229是使用--inspect标志时用于调试的默认端口,因此这就是我们要使用的端口。

Since we’ve already started our server with the previous configuration, we can go ahead and start our debug configuration. Choose the Attach to Port configuration and click play:

由于我们已经使用先前的配置启动了服务器,因此可以继续进行调试配置。 选择附加到端口配置,然后单击播放

By specifying a port, localRoot, and remoteRoot it is also possible to debug by attaching over a network connection to a remote machine.

通过指定portlocalRootremoteRoot ,还可以通过网络连接到远程计算机进行调试。

第7步—使用Nodemon调试并附加到端口 (Step 7 — Debugging with Attach to Port with Nodemon)

For our final configuration, we are going to tweak the previous one to support auto-reloading with Nodemon. Nodemon is a package, typically installed globally from npm, that will auto-reload your Node server as you save your files. This makes it much easier to make changes and test at the same time.

对于我们的最终配置,我们将调整前一个配置以支持Nodemon的自动重新加载。 Nodemon是一个软件包,通常从npm全局安装,在保存文件时会自动重新加载Node服务器。 这使得同时进行更改和测试变得容易得多。

.vscode/launch.json
.vscode / launch.json
{
  "type": "node",
  "request": "attach",
  "name": "Nodemon Debug",
  "port": 9229,
  "restart": true
},

Note: Modern versions of VS Code support a runtimeExecutable parameter which can be used for a different ‘Node.js Nodemon Setup’ configuration.

注意: VS Code的现代版本支持runtimeExecutable参数,该参数可用于不同的“ Node.js Nodemon设置”配置。

To install Nodemon, use the following command:

要安装Nodemon,请使用以下命令:

  • npm install -g nodemon

    npm install -g nodemon

Because Nodemon will auto-restart our server, we’ve set the restart property to true in the debug configuration. This way, our debugger will reconnect when our server restarts. To test this out, run your server using this command (replacing node, from earlier, with nodemon):

由于Nodemon将自动重启服务器,因此我们在调试配置中将restart属性设置为true 。 这样,调试器将在服务器重新启动时重新连接。 为了验证这一点,运行使用此命令在服务器(更换node ,从早期的,有nodemon ):

  • nodemon --inspect app.js

    nodemon-检查app.js

Then, run your configuration:

然后,运行您的配置:

Since we are using Nodemon, if we make a change to our server file and save it, our server will automatically be reloaded. We’ve defined our debug configuration to handle this scenario and reconnect as well. Make a small change to your file, save it, and make sure that your debugger reconnects when the server restarts.

由于我们正在使用Nodemon,因此,如果我们更改服务器文件并保存它,我们的服务器将自动重新加载。 我们已经定义了调试配置来处理这种情况并重新连接。 对文件进行少量更改,将其保存,并确保在服务器重新启动时调试器重新连接。

结论 (Conclusion)

In this tutorial, you set up VS Code to debug Node.js code. You now have appropriate configurations to start debugging.

在本教程中,您将设置VS Code来调试Node.js代码。 现在,您已经具有适当的配置以开始调试。

To learn more about Node.js, see our How To Code in Node series.

要了解有关Node.js的更多信息,请参阅我们的如何在Node系列中编码

翻译自: https://www.digitalocean.com/community/tutorials/how-to-debug-node-js-code-in-visual-studio-code

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值