- Get started using Node.js on Windows for beginners
- Prerequisites
- Types of Node.js applications
- Try using Node.js in VS Code
- Set up a basic web app framework by using Express
- Try using a Node.js module
- Настройка среды разработки Node.js напрямую в Windows Set up your Node.js development environment directly on Windows
- Установка nvm-windows, Node.js и npm Install nvm-windows, node.js, and npm
- Альтернативные диспетчеры версий Alternative version managers
- Установка предпочтительного редактора кода Install your favorite code editor
- Установка Git (необязательно) Install Git (optional)
Get started using Node.js on Windows for beginners
If you’re brand new to using Node.js, this guide will help you to get started with some basics.
Prerequisites
This guide assumes that you’ve already completed the steps to set up your Node.js development environment on native Windows, including:
- Install a Node.js version manager.
- Install Visual Studio Code.
Installing Node.js directly on Windows is the most straightforward way to get started performing basic Node.js operations with a minimal amount of set up.
Once you are ready to use Node.js to develop applications for production, which typically involves deploying to a Linux server, we recommend that you set up your Node.js development environment with WSL2. Though it’s possible to deploy web apps on Windows servers, it is much more common to use Linux servers to host your Node.js apps.
Types of Node.js applications
Node.js is a JavaScript runtime primarily used for creating web applications. Put another way, it’s a server-side implementation of JavaScript used for writing the backend of an application. (Though many Node.js frameworks can also handle the frontend.) Here are a few examples of what you might create with Node.js.
- Single-page apps (SPAs): These are web apps that work inside a browser and don’t need to reload a page every time you use it to get new data. Some example SPAs include social networking apps, email or map apps, online text or drawing tools, etc.
- Real-time apps (RTAs): These are web apps that enable users to receive information as soon as it’s published by an author, rather than requiring that the user (or software) check a source periodically for updates. Some example RTAs include instant messaging apps or chat rooms, online multiplayer games that can be played in the browser, online collaboration docs, community storage, video conference apps, etc.
- Data streaming apps: These are apps (or services) that send data/content as it arrives (or is created) while keeping the connection open to continue downloading further data, content, or components as needed. Some examples include video- and audio-streaming apps.
- REST APIs: These are interfaces that provide data for someone else’s web app to interact with. For example, a Calendar API service could provide dates and times for a concert venue that could be used by someone else’s local events website.
- Server-side rendered apps (SSRs): These web apps can run on both the client (in your browser / the front-end) and the server (the back-end) allowing pages that are dynamic to display (generate HTML for) whatever content is known and quickly grab content that is not known as it’s available. These are often referred to as “isomorphic” or “universal” applications. SSRs utilize SPA methods in that they don’t need to reload every time you use it. SSRs, however, offer a few benefits that may or may not be important to you, like making content on your site appear in Google search results and providing a preview image when links to your app are shared on social media like Twitter or Facebook. The potential drawback being that they require a Node.js server constantly running. In terms of examples, a social networking app that supports events that users will want to appear in search results and social media may benefit from SSR, while an email app may be fine as an SPA. You can also run server-rendered no-SPA apps, which my be something like a WordPress blog. As you can see, things can get complicated, you just need to decide what’s important.
- Command line tools: These allow you to automate repetitive tasks and then distribute your tool across the vast Node.js ecosystem. An example of a command line tool is cURL, which stand for client URL and is used to download content from an internet URL. cURL is often used to install things like Node.js or, in our case, a Node.js version manager.
- Hardware programming: While not quite as popular as web apps, Node.js is growing in popularity for IoT uses, such as collecting data from sensors, beacons, transmitters, motors, or anything that generates large amounts of data. Node.js can enable data collection, analyzing that data, communicating back and forth between a device and server, and taking action based on the analysis. NPM contains more than 80 packages for Arduino controllers, raspberry pi, Intel IoT Edison, various sensors, and Bluetooth devices.
Try using Node.js in VS Code
Open your command line (Command prompt, PowerShell, or whatever you prefer) and create a new directory: mkdir HelloNode , then enter the directory: cd HelloNode
Create a JavaScript file named «app.js» with a variable named «msg» inside: echo var msg > app.js
Open the directory and your app.js file in VS Code: : code .
Add a simple string variable («Hello World»), then send the contents of the string to your console by entering this in your «app.js» file:
To run your «app.js» file with Node.js. Open your terminal right inside VS Code by selecting View > Terminal (or select Ctrl+`, using the backtick character). If you need to change the default terminal, select the dropdown menu and choose Select Default Shell.
In the terminal, enter: node app.js . You should see the output: «Hello World».
Notice that when you type console in your ‘app.js’ file, VS Code displays supported options related to the console object for you to choose from using IntelliSense. Try experimenting with Intellisense using other JavaScript objects.
Try the new Windows terminal if you plan to use multiple command lines (Ubuntu, PowerShell, Windows Command Prompt, etc) or if you want to customize your terminal, including text, background colors, key bindings, multiple window panes, etc.
Set up a basic web app framework by using Express
Express is a minimal, flexible, and streamlined Node.js framework that makes it easier to develop a web app that can handle multiple types of requests, like GET, PUT, POST, and DELETE. Express comes with an application generator that will automatically create a file architecture for your app.
To create a project with Express.js:
- Open your command line (Command Prompt, Powershell, or whatever you prefer).
- Create a new project folder: mkdir ExpressProjects and enter that directory: cd ExpressProjects
- Use Express to create a HelloWorld project template: npx express-generator HelloWorld —view=pug
We are using the npx command here to execute the Express.js Node package without actually installing it (or by temporarily installing it depending on how you want to think of it). If you try to use the express command or check the version of Express installed using: express —version , you will receive a response that Express cannot be found. If you want to globally install Express to use over and over again, use: npm install -g express-generator . You can view a list of the packages that have been installed by npm using npm list . They’ll be listed by depth (the number of nested directories deep). Packages that you installed will be at depth 0. That package’s dependencies will be at depth 1, further dependencies at depth 2, and so on. To learn more, see Difference between npx and npm? on Stackoverflow.
Examine the files and folders that Express included by opening the project in VS Code, with: code .
The files that Express generates will create a web app that uses an architecture that can appear a little overwhelming at first. You’ll see in your VS Code Explorer window (Ctrl+Shift+E to view) that the following files and folders have been generated:
- bin . Contains the executable file that starts your app. It fires up a server (on port 3000 if no alternative is supplied) and sets up basic error handling.
- public . Contains all the publicly accessed files, including JavaScript files, CSS stylesheets, font files, images, and any other assets that people need when they connect to your website.
- routes . Contains all the route handlers for the application. Two files, index.js and users.js , are automatically generated in this folder to serve as examples of how to separate out your application’s route configuration.
- views . Contains the files used by your template engine. Express is configured to look here for a matching view when the render method is called. The default template engine is Jade, but Jade has been deprecated in favor of Pug, so we used the —view flag to change the view (template) engine. You can see the —view flag options, and others, by using express —help .
- app.js . The starting point of your app. It loads everything and begins serving user requests. It’s basically the glue that holds all the parts together.
- package.json . Contains the project description, scripts manager, and app manifest. Its main purpose is to track your app’s dependencies and their respective versions.
You now need to install the dependencies that Express uses in order to build and run your HelloWorld Express app (the packages used for tasks like running the server, as defined in the package.json file). Inside VS Code, open your terminal by selecting View > Terminal (or select Ctrl+`, using the backtick character), be sure that you’re still in the ‘HelloWorld’ project directory. Install the Express package dependencies with:
- At this point you have the framework set up for a multiple-page web app that has access to a large variety of APIs and HTTP utility methods and middleware, making it easier to create a robust API. Start the Express app on a virtual server by entering:
The DEBUG=myapp:* part of the command above means you are telling Node.js that you want to turn on logging for debugging purposes. Remember to replace ‘myapp’ with your app name. You can find your app name in the package.json file under the «name» property. Using npx cross-env sets the DEBUG environment variable in any terminal, but you can also set it with your terminal specific way. The npm start command is telling npm to run the scripts in your package.json file.
You can now view the running app by opening a web browser and going to: localhost:3000
Now that your HelloWorld Express app is running locally in your browser, try making a change by opening the ‘views’ folder in your project directory and selecting the ‘index.pug’ file. Once open, change h1= title to h1= «Hello World!» and selecting Save (Ctrl+S). View your change by refreshing the localhost:3000 URL on your web browser.
To stop running your Express app, in your terminal, enter: Ctrl+C
Try using a Node.js module
Node.js has tools to help you develop server-side web apps, some built in and many more available via npm. These modules can help with many tasks:
Tool | Used for |
---|---|
gm, sharp | Image manipulation, including editing, resizing, compression, and so on, directly in your JavaScript code |
PDFKit | PDF generation |
validator.js | String validation |
imagemin, UglifyJS2 | Minification |
spritesmith | Sprite sheet generation |
winston | Logging |
commander.js | Creating command-line applications |
Let’s use the built-in OS module to get some information about your computer’s operating system:
Настройка среды разработки 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.