Настройка среды разработки Node.js напрямую в Windows Set up your Node.js development environment directly on Windows
Ниже приведено пошаговое руководство по началу работы с Node.js в собственной среде разработки Windows. The following is a step-by-step guide to get you started using Node.js in a native Windows development environment.
Установка nvm-windows, Node.js и npm Install nvm-windows, node.js, and npm
Существует несколько способов установки Node.js. There are multiple ways to install Node.js. Мы рекомендуем использовать диспетчер версий, так как версии меняются достаточно быстро. We recommend using a version manager as versions change very quickly. Вероятно, вам придется переключаться между несколькими версиями в зависимости от потребностей для различных проектов, над которыми вы работаете. You will likely need to switch between multiple versions based on the needs of different projects you’re working on. Диспетчер версий Node Version Manager, чаще называемый nvm, является наиболее популярным средством установки нескольких версий Node.js, но он доступен только для Mac и Linux и не поддерживается в Windows. Node Version Manager, more commonly called nvm, is the most popular way to install multiple versions of Node.js, but is only available for Mac/Linux and not supported on Windows. Вместо этого выполним шаги ниже, чтобы установить nvm-windows, а затем используем его для установки Node.js и диспетчера пакетов Node Package Manager (npm). Instead, we will walk through the steps to install nvm-windows and then use it to install Node.js and Node Package Manager (npm). Существуют также альтернативные диспетчеры версий, которые описаны в следующем разделе. There are alternative version managers to consider as well covered in the next section.
Рекомендуем всегда удалять любые имеющиеся установки Node.js или npm из операционной системы перед установкой диспетчера версий, так как эти установки могут создавать необычные и запутанные конфликты. It is always recommended to remove any existing installations of Node.js or npm from your operating system before installing a version manager as the different types of installation can lead to strange and confusing conflicts. Сюда относится удаление всех существующих каталогов установки Node.js (например, C:\Program Files\nodejs), которые могут остаться. This includes deleting any existing nodejs installation directories (e.g., «C:\Program Files\nodejs») that might remain. Созданная символьная ссылка NVM не будет перезаписывать существующий (даже пустой) каталог установки. NVM’s generated symlink will not overwrite an existing (even empty) installation directory. Справку по полному удалению предыдущих установок см. здесь. For help with removing previous installations, see How to completely remove node.js from Windows.)
Откройте репозиторий windows-nvm в Интернет-браузере и щелкните ссылку Загрузить сейчас. Open the windows-nvm repository in your internet browser and select the Download Now link.
Скачайте последний выпуск файла nvm-setup.zip. Download the nvm-setup.zip file for the most recent release.
После скачивания откройте ZIP-файл, а затем запустите файл nvm-setup.exe. Once downloaded, open the zip file, then open the nvm-setup.exe file.
Мастер установки Setup-NVM-for-Windows поможет выполнить все этапы установки, в том числе выбрать каталог, в котором будут установлены репозиторий nvm-windows и Node.js. The Setup-NVM-for-Windows installation wizard will walk you through the setup steps, including choosing the directory where both nvm-windows and Node.js will be installed.
После завершения установки Once the installation is complete. откройте PowerShell и попробуйте использовать windows-nvm, чтобы просмотреть список установленных версий Node (на этом этапе их еще не должно быть): nvm ls Open PowerShell and try using windows-nvm to list which versions of Node are currently installed (should be none at this point): nvm ls
Установите текущий выпуск Node.js (в нем вы сможете протестировать новейшие улучшенные возможности, но вероятность возникновения проблем при этом будет больше, чем при использовании версии LTS) с помощью команды nvm install latest . Install the current release of Node.js (for testing the newest feature improvements, but more likely to have issues than the LTS version): nvm install latest
Установите последний стабильный выпуск LTS Node.js (рекомендуется). Для этого сначала выполните поиск номера текущей версии LTS с помощью команды nvm list available , а затем установите версию LTS по номеру с помощью команды nvm install (замените номером, например: nvm install 12.14.0 ). Install the latest stable LTS release of Node.js (recommended) by first looking up what the current LTS version number is with: nvm list available , then installing the LTS version number with: nvm install (replacing with the number, ie: nvm install 12.14.0 ).
Вызовите список установленных версий Node, выполнив команду nvm ls . Теперь в нем должны отображаться две недавно установленные версии. List what versions of Node are installed: nvm ls . now you should see the two versions that you just installed listed.
После установки требуемых версий Node.js выберите нужную версию, введя nvm use (замените нужным номером, например nvm use 12.9.0 ). After installing the Node.js version numbers you need, select the version that you would like to use by entering: nvm use (replacing with the number, ie: nvm use 12.9.0 ).
Чтобы изменить версию Node.js на ту, которую вы хотите использовать для проекта, создайте каталог проекта с помощью команды mkdir NodeTest и укажите каталог, выполнив команду cd NodeTest . Затем введите nvm use , заменив номером версии, который вы хотите использовать (т. е. версии 10.16.3). To change the version of Node.js you would like to use for a project, create a new project directory mkdir NodeTest , and enter the directory cd NodeTest , then enter nvm use replacing with the version number you’d like to use (ie v10.16.3`).
Проверьте, какая версия npm установлена, с помощью npm —version . Этот номер версии автоматически изменится на номер той версии npm, которая связана с вашей текущей версией Node.js. Verify which version of npm is installed with: npm —version , this version number will automatically change to whichever npm version is associated with your current version of Node.js.
Альтернативные диспетчеры версий Alternative version managers
Несмотря на то что windows-nvm сейчас является самым популярным менеджером версий для Node, есть несколько альтернативных вариантов: While windows-nvm is currently the most popular version manager for node, there are alternatives to consider:
nvs (Node Version Switcher) — это кроссплатформенный вариант nvm с возможностью интеграции с VS Code. nvs (Node Version Switcher) is a cross-platform nvm alternative with the ability to integrate with VS Code.
Volta — это новый диспетчер версий, созданный командой LinkedIn. Заявлено, что он отличается увеличенной скоростью и кроссплатформенной поддержкой. Volta is a new version manager from the LinkedIn team that claims improved speed and cross-platform support.
Чтобы установить Volta в качестве диспетчера версий (вместо windows-nvm), перейдите в раздел Установка Windows руководства Начало работы, затем скачайте и запустите установщик Windows, следуя инструкциям. To install Volta as your version manager (rather than windows-nvm), go to the Windows Installation section of their Getting Started guide, then download and run their Windows installer, following the setup instructions.
Перед установкой Volta необходимо убедиться, что на компьютере с Windows включен режим разработчика. You must ensure that Developer Mode is enabled on your Windows machine before installing Volta.
Дополнительные сведения об использовании Volta для установки нескольких версий Node.js в Windows см. в документации по работе с Volta. To learn more about using Volta to install multiple versions of Node.js on Windows, see the Volta Docs.
Установка предпочтительного редактора кода Install your favorite code editor
Для разработки с помощью Node.js в Windows рекомендуется установить VS Code, а также пакет расширений Node.js. We recommend you install VS Code, as well as the Node.js Extension Pack, for developing with Node.js on Windows. Установите все расширения или выберите наиболее полезные для вас. Install them all or pick and choose which seem the most useful to you.
Чтобы установить пакет расширений Node.js, сделайте следующее: To install the Node.js extension pack:
- Откройте в VS Code окно Расширения (нажав клавиши CTRL+SHIFT+X). Open the Extensions window (Ctrl+Shift+X) in VS Code.
- В поле поиска в верхней части окна расширений введите: Node Extension Pack (Пакет расширений Node) (или имя любого расширения, которое необходимо найти). In the search box at the top of the Extensions window, enter: «Node Extension Pack» (or the name of whatever extension you are looking for).
- Щелкните Установить. Select Install. После установки расширение появится в папке «Включено» в окне Расширения. Once installed, your extension will appear in the «Enabled» folder of your Extensions window. Вы можете отключить, удалить или настроить параметры, выбрав значок шестеренки рядом с описанием вашего нового расширения. You can disable, uninstall, or configure settings by selecting the gear icon next to the description of your new extension.
К дополнительным рекомендуемым расширениям относятся следующие: A few additional extensions you may want to consider include:
- Отладчик для Chrome — после завершения разработки на стороне сервера с помощью Node.js вам нужно будет выполнить разработку и тестирование на стороне клиента. Debugger for Chrome: Once you finish developing on the server side with Node.js, you’ll need to develop and test the client side. Это расширение интегрирует редактор VS Code со службой отладки браузера Chrome, что увеличивает эффективность выполнения операций. This extension integrates your VS Code editor with your Chrome browser debugging service, making things a bit more efficient.
- Раскладки клавиатуры других редакторов — эти расширения позволят использовать необходимую раскладку при переходе в другой текстовый редактор (например, Atom, Sublime, Vim, eMacs, Notepad++ и т. п.). Keymaps from other editors: These extensions can help your environment feel right at home if you’re transitioning from another text editor (like Atom, Sublime, Vim, eMacs, Notepad++, etc).
- Расширение синхронизации параметров — позволяет синхронизировать параметры VS Code в разных установках, используя GitHub. Settings Sync: Enables you to synchronize your VS Code settings across different installations using GitHub. Если вы работаете на разных компьютерах, это обеспечит согласованность среды между ними. If you work on different machines, this helps keep your environment consistent across them.
Установка Git (необязательно) Install Git (optional)
Если вы планируете работать совместно с другими пользователями или размещать проект на сайте с открытым исходным кодом (например, GitHub), примите во внимание, что VS Code поддерживает управление версиями с помощью Git. If you plan to collaborate with others, or host your project on an open-source site (like GitHub), VS Code supports version control with Git. Вкладка системы управления версиями в VS Code отслеживает все изменения и содержит общие команды Git (добавление, фиксация, принудительная отправка, извлечение) прямо в пользовательском интерфейсе. The Source Control tab in VS Code tracks all of your changes and has common Git commands (add, commit, push, pull) built right into the UI. Сначала необходимо установить Git для включения панели управления версиями. You first need to install Git to power the Source Control panel.
Скачайте и установите Git для Windows с веб-сайта git-scm. Download and install Git for Windows from the git-scm website.
В комплект входит мастер установки, который задает вам ряд вопросов о параметрах установки Git. An Install Wizard is included that will ask you a series of questions about settings for your Git installation. Рекомендуется использовать все параметры по умолчанию, если у вас нет конкретной причины изменить какой-либо из них. We recommend using all of the default settings, unless you have a specific reason for changing something.
Если вы никогда не использовали Git, обратитесь к руководствам по GitHub. Они помогут вам приступить к работе. If you’ve never worked with Git before, GitHub Guides can help you get started.
Учебник. Создание приложения Node.js и Express в Visual Studio Tutorial: Create a Node.js and Express app in Visual Studio
В этом учебнике по разработке с помощью Node.js и Express в Visual Studio вы создадите простое веб-приложение Node.js, добавите в него код, изучите некоторые возможности интегрированной среды разработки и запустите приложение. In this tutorial for Visual Studio development using Node.js and Express, you create a simple Node.js web application, add some code, explore some features of the IDE, and run the app.
Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
В этом руководстве вы узнаете, как: In this tutorial, you learn how to:
- Создание проекта Node.js Create a Node.js project
- Добавление кода Add some code
- Использование IntelliSense для редактирования кода Use IntelliSense to edit code
- Запуск приложения Run the app
- Достижение точки останова в отладчике Hit a breakpoint in the debugger
Подготовка к работе Before you begin
Ниже приведен краткий список вопросов и ответов, с помощью которого вы сможете ознакомиться с некоторыми основными понятиями. Here’s a quick FAQ to introduce you to some key concepts.
Что такое Node.js? What is Node.js?
Node.js — это серверная среда выполнения JavaScript, выполняющая сценарии JavaScript на стороне сервера. Node.js is a server-side JavaScript runtime environment that executes JavaScript server-side.
Что такое npm? What is npm?
npm — это диспетчер пакетов по умолчанию для Node.js. npm is the default package manager for the Node.js. Диспетчер пакетов упрощает публикацию и совместное использование исходного кода библиотек Node.js. Он предназначен для упрощения установки, обновления и удаления библиотек. The package manager makes it easier for programmers to publish and share source code of Node.js libraries and is designed to simplify installation, updating, and uninstallation of libraries.
Что такое express? What is express?
Express — это платформа веб-приложений, используемая в качестве серверной платформы Node.js для сборки веб-приложений. Express is a web application framework, used as a server framework for Node.js to build web applications. Express позволяет выбирать различные платформы для создания внешнего пользовательского интерфейса, например Pug (в прошлом — Jade). Express allows you to choose different front-end frameworks to create a UI, such as Pug (formerly called Jade). В этом учебнике используется Pug. Pug is used in this tutorial.
Предварительные требования Prerequisites
У вас должна быть установлена среда Visual Studio и должна иметься рабочая нагрузка «Разработка Node.js». You must have Visual Studio installed and the Node.js development workload.
Установите Visual Studio 2019 бесплатно со страницы скачиваемых материалов Visual Studio , если вы еще не сделали этого. If you haven’t already installed Visual Studio 2019, go to the Visual Studio downloads page to install it for free.
Установите Visual Studio 2017 бесплатно со страницы скачиваемых материалов Visual Studio , если вы еще не сделали этого. If you haven’t already installed Visual Studio 2017, go to the Visual Studio downloads page to install it for free.
Если вам нужно установить рабочую нагрузку, но вы уже используете Visual Studio, выберите пункт Средства > Получить средства и компоненты. , после чего запустится Visual Studio Installer. If you need to install the workload but already have Visual Studio, go to Tools > Get Tools and Features. , which opens the Visual Studio Installer. Выберите рабочую нагрузку Разработка Node.js, а затем элемент Изменить. Choose the Node.js development workload, then choose Modify.
У вас должна быть установлена среда выполнения Node.js. You must have the Node.js runtime installed.
Если он не установлен, мы рекомендуем установить версию LTS с веб-сайта Node.js для обеспечения лучшей совместимости с внешними платформами и библиотеками. If you don’t have it installed, we recommend you install the LTS version from the Node.js website for best compatibility with outside frameworks and libraries. Node.js построен для 32-разрядных и 64-разрядных архитектур. Node.js is built for 32-bit and 64-bit architectures. Средства Node.js в Visual Studio, включенные в рабочую нагрузку Node.js, поддерживают обе версии. The Node.js tools in Visual Studio, included in the Node.js workload, support both versions. Однако требуется только одна, поскольку программа установки Node.js поддерживает только одну установку за раз. Only one is required and the Node.js installer only supports one being installed at a time.
Как правило, Visual Studio автоматически обнаруживает установленную среду выполнения Node.js. In general, Visual Studio automatically detects the installed Node.js runtime. Если установленная среда выполнения не обнаружена, вы можете настроить проект так, чтобы он ссылался на установленную среду выполнения, на странице свойств (после создания проекта щелкните его узел правой кнопкой мыши, выберите пункт Свойства и укажите путь Node.exe). If it does not detect an installed runtime, you can configure your project to reference the installed runtime in the properties page (after you create a project, right-click the project node, choose Properties, and set the Node.exe path). Можно использовать глобальную установку Node.js или указать путь к локальному интерпретатору в каждом из проектов Node.js. You can use a global installation of Node.js or you can specify the path to a local interpreter in each of your Node.js projects.
Этот учебник был протестирован с Node.js 8.10.0. This tutorial was tested with Node.js 8.10.0.
Создание проекта Node.js Create a new Node.js project
Visual Studio управляет файлами для отдельного приложения в проекте. Visual Studio manages files for a single application in a project. Проект включает исходный код, ресурсы и файлы конфигурации. The project includes source code, resources, and configuration files.
В этом учебнике вы начнете работу с простого проекта, содержащего код для приложения Node.js и express. In this tutorial, you begin with a simple project containing code for a Node.js and express app.
Запустите Visual Studio. Open Visual Studio.
Создайте новый проект. Create a new project.
Нажмите клавишу ESC, чтобы закрыть окно запуска. Press Esc to close the start window. Нажмите CTRL+Q, чтобы открыть поле поиска, введите Node.js и выберите Create a new Basic Azure Node.js Express 4 application (Создать простое приложение Node.js Express 4 в Azure) (JavaScript). Type Ctrl + Q to open the search box, type Node.js, then choose Create a new Basic Azure Node.js Express 4 application (JavaScript). В появившемся диалоговом окне выберите Создать. In the dialog box that appears, choose Create.
В верхней строке меню последовательно выберите Файл > Создать > Проект. From the top menu bar, choose File > New > Project. В левой области диалогового окна Новый проект разверните узел JavaScript и выберите Node.js. In the left pane of the New Project dialog box, expand JavaScript, then choose Node.js. В средней области выберите Базовое приложение Azure Node.js Express 4 и нажмите кнопку ОК. In the middle pane, choose Basic Azure Node.js Express 4 application, then choose OK.
Если шаблон проекта Базовое приложение Azure Node.js Express 4 отсутствует, необходимо добавить рабочую нагрузку Разработка Node.js. If you don’t see the Basic Azure Node.js Express 4 application project template, you must add the Node.js development workload. Подробные инструкции см. в разделе с предварительными требованиями. For detailed instructions, see the Prerequisites.
Visual Studio создаст решение и откроет проект в правой области. Visual Studio creates the new solution and opens your project in the right pane. Файл app.js проекта откроется в редакторе (в левой области). The app.js project file opens in the editor (left pane).
(1) Полужирным шрифтом выделен ваш проект, имя которого вы указали в окне Новый проект. (1) Highlighted in bold is your project, using the name you gave in the New Project dialog box. В файловой системе этот проект представлен файлом NJSPROJ в папке проекта. In the file system, this project is represented by a .njsproj file in your project folder. Вы можете задать свойства и переменные среды, связанные с проектом, щелкнув его правой кнопкой мыши и выбрав пункт Свойства. You can set properties and environment variables associated with the project by right-clicking the project and choosing Properties. Вы можете одновременно использовать и другие средства разработки, так как файл проекта не вносит изменения в источник проекта Node.js. You can do round-tripping with other development tools, because the project file does not make custom changes to the Node.js project source.
(2) На верхнем уровне находится решение, имя которого по умолчанию совпадает с именем проекта. (2) At the top level is a solution, which by default has the same name as your project. Решение, представленное на диске файлом SLN, является контейнером для одного или нескольких связанных проектов. A solution, represented by a .sln file on disk, is a container for one or more related projects.
(3) В узле npm представлены все установленные пакеты npm. (3) The npm node shows any installed npm packages. Вы можете щелкнуть узел npm правой кнопкой мыши, чтобы найти и установить пакеты npm с помощью диалогового окна. Кроме того, установить и обновить пакеты можно с помощью параметров, доступных в файле package.json и контекстном меню узла npm. You can right-click the npm node to search for and install npm packages using a dialog box or install and update packages using the settings in package.json and right-click options in the npm node.
(4) package.json — это файл, используемый npm для управления зависимостями и версиями пакетов для локально установленных пакетов. (4) package.json is a file used by npm to manage package dependencies and package versions for locally-installed packages. Дополнительные сведения см. в разделе Управление пакетами npm. For more information, see Manage npm packages.
(5) Файлы проекта, такие как app.js, отображаются в узле проекта. (5) Project files such as app.js show up under the project node. app.js — это файл запуска проекта, поэтому он выделяется полужирным шрифтом. app.js is the project startup file and that is why it shows up in bold. Задать файл запуска можно, щелкнув правой кнопкой мыши файл в проекте и выбрав Задать как файл запуска Node.js. You can set the startup file by right-clicking a file in the project and selecting Set as Node.js startup file.
Откройте узел npm и проверьте наличие необходимых пакетов npm. Open the npm node and make sure that all the required npm packages are present.
Если каких-либо пакетов не хватает (имеется значок с восклицательным знаком), можно щелкнуть правой кнопкой мыши узел npm и выбрать пункт Установить пакеты npm. If any packages are missing (exclamation point icon), you can right-click the npm node and choose Install npm Packages.
Добавление кода Add some code
Приложение использует Pug в качестве внешней платформы JavaScript. The application uses Pug for the front-end JavaScript framework. Pug использует простой код разметки, который компилируется в HTML. Pug uses simple markup code that compiles to HTML. (Среда Pug задана в качестве обработчика представлений в файле app.js. (Pug is set as the view engine in app.js. Код, который задает обработчик представлений в app.js, — app.set(‘view engine’, ‘pug’); .) The code that sets the view engine in app.js is app.set(‘view engine’, ‘pug’); .)
В обозревателе решений (правая область) откройте папку представлений, а затем откройте файл index.pug. In Solution Explorer (right pane), open the views folder, then open index.pug.
Замените содержимое следующей разметкой: Replace the content with the following markup.
Предыдущий код используется для динамического создания HTML-страницы с заголовком и приветственным сообщением. The preceding code is used to dynamically generate an HTML page with a title and welcome message. Страница также содержит код, позволяющий отображать изображение, которое изменяется при каждом нажатии кнопки. The page also includes code to display an image that changes whenever you press a button.
В папке маршрутов откройте файл index.js. In the routes folder, open index.js.
Добавьте следующий код перед вызовом router.get : Add the following code before the call to router.get :
Этот код создает объект данных, который передается на динамически созданную HTML-страницу. This code creates a data object that you pass to the dynamically generated HTML page.
Замените вызов функции router.get следующим кодом: Replace the router.get function call with the following code:
Предыдущий код задает текущую страницу с помощью объекта маршрутизатора Express и отображает ее, передавая объект заголовка и данных. The preceding code sets the current page using the Express router object and renders the page, passing the title and data object to the page. Файл index.pug указан здесь в качестве страницы для загрузки при запуске index.js. The index.pug file is specified here as the page to load when index.js runs. index.js настраивается в качестве маршрута по умолчанию в коде app.js (не показано). index.js is configured as the default route in app.js code (not shown).
Чтобы продемонстрировать несколько возможностей Visual Studio, мы намеренно добавили ошибку в строку кода, содержащего функцию res.render . To demonstrate several features of Visual Studio, there’s a deliberate error in the line of code containing res.render . Необходимо исправить эту ошибку, прежде чем запустить приложение в следующем разделе. You need to fix the error before the app can run, which you do in the next section.
Использование IntelliSense Use IntelliSense
IntelliSense — это средство Visual Studio, которое помогает при написании кода. IntelliSense is a Visual Studio tool that assists you as you write code.
В файле index.js перейдите к строке кода, содержащей res.render . In index.js, go to the line of code containing res.render .
Установите курсор в конце строки data , введите : get , и IntelliSense покажет функцию getData , определенную ранее в этом коде. Put your cursor after the data string, type : get and IntelliSense will show you the getData function defined earlier in the code. Выберите getData . Select getData .
Добавьте круглые скобки, чтобы сформировать вызов функции ( getData() ). Add the parentheses to make it a function call, getData() .
Удалите запятую ( , ) перед элементом «data» , и выражение будет выделено зеленым цветом (подсветка синтаксиса). Remove the comma ( , ) before «data» and you see green syntax highlighting on the expression. Наведите указатель на подсветку синтаксиса. Hover over the syntax highlighting.
В последней строке этого сообщения указывается, что интерпретатор JavaScript ожидал запятую ( , ). The last line of this message tells you that the JavaScript interpreter expected a comma ( , ).
В нижней области откройте вкладку Список ошибок и выберите Cборка + IntelliSense для типа сообщаемых проблем. In the lower pane, click the Error List tab and select Build + IntelliSense for the type of issues reported.
Вы увидите предупреждение и описание, а также имя файла и номер строки. You see the warning and description along with the filename and line number.
Исправьте код, добавив запятую ( , ) перед элементом «data» . Fix the code by adding the comma ( , ) before «data» .
Исправленная строка кода должна выглядеть следующим образом: res.render(‘index’, < title: 'Express', "data": getData() >); When corrected, line of code should look like this: res.render(‘index’, < title: 'Express', "data": getData() >);
Установка точки останова Set a breakpoint
Затем вы запустите приложение с подключенным отладчиком Visual Studio. You’re next going to run the app with the Visual Studio debugger attached. Но сначала задайте точку останова. Before doing that, you need to set a breakpoint.
В файле index.js щелкните в левом внешнем поле перед следующей строкой кода, чтобы установить точку останова: In index.js, click in the left gutter before the following line of code to set a breakpoint:
Точки останова — это один из самых простых и важных компонентов надежной отладки. Breakpoints are the most basic and essential feature of reliable debugging. Точка останова указывает, где Visual Studio следует приостановить выполнение кода, чтобы вы могли проверить значения переменных или поведение памяти либо выполнение ветви кода. A breakpoint indicates where Visual Studio should suspend your running code so you can take a look at the values of variables, or the behavior of memory, or whether or not a branch of code is getting run.
Запуск приложения Run the application
На панели инструментов отладки выберите целевой объект отладки, например веб-сервер(Google Chrome) или веб-сервер (Microsoft Edge) . Select the debug target in the Debug toolbar, such as Web Server (Google Chrome) or Web Server (Microsoft Edge).
Если Chrome установлен на вашем компьютере, но отсутствует в списке, выберите Просмотреть с помощью в раскрывающемся списке целевых объектов отладки, а затем установите Chrome в качестве целевого объекта отладки по умолчанию (выберите По умолчанию). If Chrome is available on your machine, but does not show up as an option, choose Browse With from the debug target dropdown list, and select Chrome as the default browser target (choose Set as Default).
Чтобы запустить приложение, нажмите клавишу F5 (Отладка > Начать отладку). Press F5 (Debug > Start Debugging) to run the application.
Отладчик приостановит выполнение в заданной точке останова. The debugger pauses at the breakpoint you set. Теперь можно изучить состояние приложения. Now, you can inspect your app state.
Наведите указатель на функцию getData , чтобы увидеть ее свойства в подсказке по данным. Hover over getData to see its properties in a DataTip
Чтобы продолжить, нажмите клавишу F5 (Отладка > Продолжить). Press F5 (Debug > Continue) to continue.
Приложение откроется в браузере. The app opens in a browser.
В окне браузера вы увидите заголовок «Express» и фразу «Welcome to Express» в первом абзаце. In the browser window, you will see «Express» as the title and «Welcome to Express» in the first paragraph.
Нажимайте кнопки, чтобы просмотреть различные изображения. Click the buttons to display different images.
Закройте веб-браузер. Close the web browser.
(Необязательно) Публикация в Службу приложений Azure (Optional) Publish to Azure App Service
В обозревателе решений щелкните проект правой кнопкой мыши и выберите пункт Опубликовать. In Solution Explorer, right-click the project and choose Publish.
Выберите цель Служба приложений Microsoft Azure. Choose Microsoft Azure App Service.
В диалоговом окне Служба приложений можно войти в учетную запись Azure и подключиться к существующим подпискам Azure. In the App Service dialog box, you can sign into your Azure account and connect to existing Azure subscriptions.
Выполните дальнейшие инструкции, чтобы выбрать подписку, выбрать или создать группу ресурсов, выбрать или создать план службы приложений, а затем, когда будет предложено, выполните инструкции по публикации в Azure. Follow the remaining steps to select a subscription, choose or create a resource group, choose or create an app service plane, and then follow the steps when prompted to publish to Azure. Более подробные инструкции см. на странице Публикация на веб-сайте Azure с помощью веб-развертывания. For more detailed instructions, see Publish to Azure website using web deploy.
В окне Вывод показан ход выполнения развертывания в Azure. The Output window shows progress on deploying to Azure.
После успешного развертывания в браузере откроется приложение, выполняющееся в Службе приложений Azure. On successful deployment, your app opens in a browser running in Azure App Service. Нажмите кнопку, чтобы отобразить изображение. Click a button to display an image.
Поздравляем с завершением этого учебника! Congratulations on completing this tutorial!