Node.js tutorial in Visual Studio Code
Node.js is a platform for building fast and scalable server applications using JavaScript. Node.js is the runtime and npm is the Package Manager for Node.js modules.
Visual Studio Code has support for the JavaScript and TypeScript languages out-of-the-box as well as Node.js debugging. However, to run a Node.js application, you will need to install the Node.js runtime on your machine.
To get started in this walkthrough, install Node.js for your platform. The Node Package Manager is included in the Node.js distribution. You’ll need to open a new terminal (command prompt) for the node and npm command-line tools to be on your PATH.
To test that you have Node.js installed correctly on your computer, open a new terminal and type node —version and you should see the current Node.js version installed.
Linux: There are specific Node.js packages available for the various flavors of Linux. See Installing Node.js via package manager to find the Node.js package and installation instructions tailored to your version of Linux.
Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Node.js development. You can run Linux distributions on Windows and install Node.js into the Linux environment. When coupled with the WSL extension, you get full VS Code editing and debugging support while running in the context of WSL. To learn more, go to Developing in WSL or try the Working in WSL tutorial.
Hello World
Let’s get started by creating the simplest Node.js application, «Hello World».
Create an empty folder called «hello», navigate into and open VS Code:
mkdir hello cd hello code .
Tip: You can open files or folders directly from the command line. The period ‘.’ refers to the current folder, therefore VS Code will start and open the Hello folder.
From the File Explorer toolbar, press the New File button:
and name the file app.js :

By using the .js file extension, VS Code interprets this file as JavaScript and will evaluate the contents with the JavaScript language service. Refer to the VS Code JavaScript language topic to learn more about JavaScript support.
Create a simple string variable in app.js and send the contents of the string to the console:
var msg = 'Hello World'; console.log(msg);
Note that when you typed console. IntelliSense on the console object was automatically presented to you.

Also notice that VS Code knows that msg is a string based on the initialization to ‘Hello World’ . If you type msg. you’ll see IntelliSense showing all of the string functions available on msg .

After experimenting with IntelliSense, revert any extra changes from the source code example above and save the file ( ⌘S (Windows, Linux Ctrl+S ) ).
Running Hello World
It’s simple to run app.js with Node.js. From a terminal, just type:
node app.js
You should see «Hello World» output to the terminal and then Node.js returns.
Integrated Terminal
VS Code has an integrated terminal which you can use to run shell commands. You can run Node.js directly from there and avoid switching out of VS Code while running command-line tools.
View > Terminal ( ⌃` (Windows, Linux Ctrl+` ) with the backtick character) will open the integrated terminal and you can run node app.js there:

For this walkthrough, you can use either an external terminal or the VS Code integrated terminal for running the command-line tools.
Debugging Hello World
As mentioned in the introduction, VS Code ships with a debugger for Node.js applications. Let’s try debugging our simple Hello World application.
To set a breakpoint in app.js , put the editor cursor on the first line and press F9 or click in the editor left gutter next to the line numbers. A red circle will appear in the gutter.

To start debugging, select the Run and Debug view in the Activity Bar:
![]()
You can now click Debug toolbar green arrow or press F5 to launch and debug «Hello World». Your breakpoint will be hit and you can view and step through the simple application. Notice that VS Code displays a different colored Status Bar to indicate it is in Debug mode and the DEBUG CONSOLE is displayed.

Now that you’ve seen VS Code in action with «Hello World», the next section shows using VS Code with a full-stack Node.js web app.
Note: We’re done with the «Hello World» example so navigate out of that folder before you create an Express app. You can delete the «Hello» folder if you want as it is not required for the rest of the walkthrough.
An Express application
Express is a very popular application framework for building and running Node.js applications. You can scaffold (create) a new Express application using the Express Generator tool. The Express Generator is shipped as an npm module and installed by using the npm command-line tool npm .
Tip: To test that you’ve got npm correctly installed on your computer, type npm —help from a terminal and you should see the usage documentation.
Install the Express Generator by running the following from a terminal:
npm install -g express-generator
The -g switch installs the Express Generator globally on your machine so you can run it from anywhere.
We can now scaffold a new Express application called myExpressApp by running:
express myExpressApp --view pug
This creates a new folder called myExpressApp with the contents of your application. The —view pug parameters tell the generator to use the pug template engine.
To install all of the application’s dependencies (again shipped as npm modules), go to the new folder and execute npm install :
cd myExpressApp npm install
At this point, we should test that our application runs. The generated Express application has a package.json file which includes a start script to run node ./bin/www . This will start the Node.js application running.
From a terminal in the Express application folder, run:
npm start
The Node.js web server will start and you can browse to http://localhost:3000 to see the running application.

Great code editing
Close the browser and from a terminal in the myExpressApp folder, stop the Node.js server by pressing CTRL+C .
Now launch VS Code:
code .
Note: If you’ve been using the VS Code integrated terminal to install the Express generator and scaffold the app, you can open the myExpressApp folder from your running VS Code instance with the File > Open Folder command.
The Node.js and Express documentation does a great job explaining how to build rich applications using the platform and framework. Visual Studio Code will make you more productive in developing these types of applications by providing great code editing and navigation experiences.
Open the file app.js and hover over the Node.js global object __dirname . Notice how VS Code understands that __dirname is a string. Even more interesting, you can get full IntelliSense against the Node.js framework. For example, you can require http and get full IntelliSense against the http class as you type in Visual Studio Code.

VS Code uses TypeScript type declaration (typings) files (for example node.d.ts ) to provide metadata to VS Code about the JavaScript based frameworks you are consuming in your application. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience. Thanks to a feature called Automatic Type Acquisition , you do not have to worry about downloading these type declaration files, VS Code will install them automatically for you.
You can also write code that references modules in other files. For example, in app.js we require the ./routes/index module, which exports an Express.Router class. If you bring up IntelliSense on index , you can see the shape of the Router class.

Debug your Express app
You will need to create a debugger configuration file launch.json for your Express application. Click on Run and Debug in the Activity Bar ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ) and then select the create a launch.json file link to create a default launch.json file. Select the Node.js environment by ensuring that the type property in configurations is set to «node» . When the file is first created, VS Code will look in package.json for a start script and will use that value as the program (which in this case is «$\\bin\\www ) for the Launch Program configuration.
"version": "0.2.0", "configurations": [ "type": "node", "request": "launch", "name": "Launch Program", "program": "$ \\bin\\www" > ] >
Save the new file and make sure Launch Program is selected in the configuration dropdown at the top of the Run and Debug view. Open app.js and set a breakpoint near the top of the file where the Express app object is created by clicking in the gutter to the left of the line number. Press F5 to start debugging the application. VS Code will start the server in a new terminal and hit the breakpoint we set. From there you can inspect variables, create watches, and step through your code.

Deploy your application
If you’d like to learn how to deploy your web application, check out the Deploying Applications to Azure tutorials where we show how to run your website in Azure.
Next steps
There is much more to explore with Visual Studio Code, please try the following topics:
- Node.js profile template — Create a new profile with a curated set of extensions, settings, and snippets.
- Settings — Learn how to customize VS Code for how you like to work.
- Debugging — This is where VS Code really shines.
- Video: Getting started with Node.js debugging — Learn how to attach to a running Node.js process.
- Node.js debugging — Learn more about VS Code’s built-in Node.js debugging.
- Debugging recipes — Examples for scenarios like client-side and container debugging.
- Tasks — Running tasks with Gulp, Grunt and Jake. Showing Errors and Warnings.
Как настроить VS Code для разработки на JavaScript
Visual Studio Code – популярный бесплатный редактор кода, созданный Microsoft’ом для программистов. VS Code никак не связан с Visual Studio. VS Code работает быстрее Атома, активно развивается и легко расширяется плагинами.
- отладчик кода
- встроенный терминал
- удобные инструменты для работы с Git
- подсветка синтаксиса для множества популярных языков и файловых форматов
- удобная навигация
- встроенный предпросмотр Markdown
- умное автодополнение
- встроенный пакетный менеджер
Пакетный менеджер нужен для установки и удаления пакетов расширений (плагинов). Для удобной разработки на JavaScript для бэкенда и фронтенда нужно установить несколько пакетов.

Для установки нового пакета зайдите в выпадающее меню «View» на вкладку «Extensions» и введите название пакета в строке поиска, а затем нажмите кнопку «Install».
Babel и ES6
VS Code содержит понятие «сборки проекта». Редактор можно настроить таким образом, чтобы сборка JavaScript-проекта заключалась в конвертации кода из ES6 в читаемый ES5 с Source Maps с помощью Babel.
Добавьте таск (задание) в файл tasks.json в директории .vscode в корне вашего проекта:
"version": "2.0.0", "type": "shell", "tasks": [ "label": "watch", "command": "$/node_modules/.bin/babel src --out-dir dist -w --source-maps", "group": "build", "isBackground": true > ] >
Теперь комбинация клавиш Shift+Ctrl+B (Windows/Linux) или Shift+CMD+B (macOS) запустит сборку.
Стандарты кодирования
Eslint – это утилита, проверяющая стандарты кодирования на JavaScript. Стандарт де-факто в мире JS.

Нужно сначала установить eslint в системе, а потом установить расширение VS Code, которое будет использовать установленный линтер. Есть разные способы интеграции линтера с расширением. Мы рассмотрим установку линтера глобально в системе.
- Установите Node.js, используя пакетный менеджер вашей операционной системы.
- Установите eslint командой npm install -g eslint . Вероятно, вам понадобится использовать sudo .
- Установите плагины, которые конфигурируют eslint . Без них (по умолчанию) eslint ничего не проверяет.
npm install -g eslint-config-airbnb-base eslint-plugin-import
extends: - 'airbnb-base' env: node: true browser: true
Автоматическое дополнение
VS Code содержит мощную систему анализа кода для автодополнений и подсказок – IntelliSense.
IntelliSense работает сразу, но для настройки деталей нужно создать конфигурационный файл jsconfig.json .
jsconfig.json
Если положить в корень директории с JavaScript-проектом конфигурационный файл jsconfig.json , то VS Code будет использовать эту конфигурацию для работы с вашим проектом. Вот пример такого файла:
"compilerOptions": "target": "ES6" >, "exclude": [ "node_modules", "**/node_modules/*" ] >
Здесь можно настроить, например, какие директории стоит исключить из системы автодополнений IntelliSense. VS Code совместим с node, webpack, bower, ember и другими популярными инструментами. Полная документация по jsconfig доступна на сайте VS Code.
Отладка
VS Code содержит встроенный отладчик кода. Вы можете, например, отметить брейкпойнты (точки остановки) и следить за состоянием приложения в реальном времени.
Для отладки бэкенд-кода достаточно встроенных возможностей. Для отладки фронтенд-кода нужно установить плагин для соответствующего браузера:
- Debugger for Chrome
- Debugger for Firefox
- Debugger for Edge
Подробнее об отладке можно узнать на сайте VS Code.
Ссылки
Курс по настройке окружения для работы в современной экосистеме JavaScript.
Запустить JavaScript в коде Visual Studio
Есть ли способ выполнить JavaScript и отобразить результаты с помощью кода Visual Studio ?
Например, файл сценария, содержащий:
console.log('hello world');
Я предполагаю, что понадобится Node.js, но не могу понять, как это сделать?
Под кодом Visual Studio я подразумеваю новый редактор кода от Microsoft — Код написан не с использованием Visual Studio.
Nick Le Page 3 Авг 2015 в 04:55
18 ответов
Лучший ответ
Это решение предназначено для запуска текущего открытого файла в узле и вывода результатов в VSCode.
У меня был тот же вопрос, и я обнаружил, что недавно представленный tasks полезен для этого конкретного случая использования. Это немного хлопотно, но вот что я сделал:
Создайте каталог .vscode в корне вашего проекта и создайте в нем файл tasks.json . Добавьте это определение задачи в файл:
Тогда ты можешь: press F1 > type `run task` > enter > select `runFile` > enter для запуска вашей задачи, но мне было проще добавить настраиваемую привязку клавиш для открытия списков задач.
Чтобы добавить привязку клавиш, в меню пользовательского интерфейса VSCode выберите «Код»> «Настройки»> «Сочетания клавиш». Добавьте это к своим сочетаниям клавиш:
Конечно, вы можете выбрать любую комбинацию клавиш.
ОБНОВЛЕНИЕ:
Предполагая, что вы запускаете код JavaScript для его тестирования , вы можете пометить свою задачу как задачу test , установив для нее isTestCommand свойство с true , а затем вы можете привязать ключ к workbench.action.tasks.test команда для вызова с одним действием.
Другими словами, ваш файл tasks.json теперь будет содержать:
. и ваш файл keybindings.json теперь будет содержать:
Olivier Dagenais 13 Дек 2016 в 21:34
Другой способ — открыть терминал ctrl + ` execute node . Теперь у вас активен узел REPL. Теперь вы можете отправить свой файл или выделенный текст в терминал. Для этого откройте VSCode палитру команд ( F1 или ctrl + shift + p ) и выполните >run selected text in active terminal или >.
Если вам нужен чистый REPL перед выполнением кода, вам придется перезапустить узел REPL. Это делается в Терминале с узлом REPL ctrl+c ctrl+c для выхода и вводом node для начала.
Вероятно, вы могли бы привязать команды палитры команд к любой клавише, которую хотите.
PS: node должен быть установлен и на вашем пути
h3dkandi 15 Мар 2019 в 09:23
Для Windows : просто измените связь файла .js на node.exe
1) Take VSCode 2) Right click on the file in left pane 3) Click "Reveal in explorer" from context menu 4) Right click on the file -> Select "Open with" -> Select "Choose another program" 5) Check box "Always use this app to open .js file" 6) Click "More apps" -> "Look for another app in PC" 7) Navigate to node.js installation directory.(Default C:\Program Files\nodejs\node.exe" 8) Click "Open" and you can just see cmd flashing 9) Restart vscode and open the file -> Terminal Menu -> "Run active file".
Harikrishnan 12 Сен 2019 в 04:03
Другой вариант — использовать консоль инструментов разработчика в Visual Studio Code. Просто выберите «Переключить инструменты разработчика» в меню справки, а затем выберите вкладку «Консоль» во всплывающих окнах инструментов разработчика. Оттуда у вас есть те же инструменты разработки REPL, что и в Chrome.
Alex Broadwin 10 Май 2019 в 16:30
Есть много способов запустить javascript в Visual Studio Code.
Если вы используете Node, то рекомендую использовать стандартный отладчик в VSC.
Обычно я создаю фиктивный файл, например test.js, в котором провожу внешние тесты.
В папке, где находится ваш код, вы создаете папку с именем «.vscode» и создаете файл с именем «launch.json».
В этот файл вы вставляете следующее и сохраняете. Теперь у вас есть два варианта тестирования вашего кода.
Когда вы выбираете «Nodemon Test File», вам нужно поместить свой код для тестирования в test.js.
Чтобы установить nodemon и получить дополнительную информацию о том, как отлаживать с помощью nodemon в VSC, я рекомендую прочитать это статья, в которой более подробно объясняется вторая часть файла launch.json и способы отладки в ExpressJS.
< "version": "0.2.0", "configurations": [ < "type": "node", "request": "launch", "name": "Nodemon Test File", "runtimeExecutable": "nodemon", "program": "$/test.js", "restart": true, "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" >, < "type": "node", "request": "attach", "name": "Node: Nodemon", "processId": "$", "restart": true, "protocol": "inspector", >, ] >
Isak La Fleur 3 Апр 2019 в 16:06
Просто установите nodemon и запустите
nodemon your_file.js
На терминале vs code.
davimdantas 21 Дек 2019 в 18:51
Я бы посоветовал вам использовать простой и легкий плагин под названием Quokka, который очень популярен в наши дни и помогает вам отлаживать код на ходу. Quokka.js. Одним из самых больших преимуществ использования этого плагина является то, что вы экономите много времени, чтобы перейти в веб-браузер и оценить свой код, с его помощью вы можете видеть все, что происходит в коде VS, что экономит много времени.
Srijan Chaudhary 13 Дек 2019 в 00:50
Нет необходимости устанавливать среду для запуска кода на javascript, python и т. Д. В коде Visual Studio, что вам нужно сделать, это просто установить расширение Code Runner, а затем просто выбрать часть кода, которую вы хотите запустить, и нажать кнопка запуска присутствует в правом верхнем углу.
Aman Mishra 2 Июн 2019 в 19:07
Теперь это может быть проще всего, начиная с версии 1.32:
< "key": "ctrl+shift+t", "command": "workbench.action.terminal.sendSequence", "args": < "text": "node '$'\u000D" > >
Используйте собственную привязку клавиш.
С vscode v1.32 вы можете sendSequence подключаться к терминалу, используя такие переменные, как $ , который является текущим файлом. Если вам нужен другой путь, замените $ на свой путь в приведенной выше привязке клавиш.
\u000D — это возврат, поэтому он будет выполнен немедленно.
Я добавил ‘ вокруг переменной $ на случай, если в пути к вашему файлу есть пробелы, как c:Users\Some Directory\fileToRun
Mark 12 Мар 2019 в 03:05
Это очень просто, когда вы создаете новый файл в VS Code и запускаете его, если у вас еще нет файла конфигурации, он создает его для вас, единственное, что вам нужно настроить, это значение «программы» и установить его. на путь к вашему основному файлу JS, выглядит так:
< "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. // ONLY "node" and "mono" are supported, change "type" to switch. // ABSOLUTE paths are required for no folder workspaces. "configurations": [ < // Name of configuration; appears in the launch configuration drop down menu. "name": "Launch", // Type of configuration. Possible values: "node", "mono". "type": "node", // ABSOLUTE path to the program. "program": "C:\\test.js", //HERE YOU PLACE THE MAIN JS FILE // Automatically stop program after launch. "stopOnEntry": false, // Command line arguments passed to the program. "args": [], // ABSOLUTE path to the working directory of the program being debugged. Default is the directory of the program. "cwd": "", // ABSOLUTE path to the runtime executable to be used. Default is the runtime executable on the PATH. "runtimeExecutable": null, // Optional arguments passed to the runtime executable. "runtimeArgs": [], // Environment variables passed to the program. "env": < >, // Use JavaScript source maps (if they exist). "sourceMaps": false, // If JavaScript source maps are enabled, the generated code is expected in this directory. "outDir": null >, < "name": "Attach", "type": "node", // TCP/IP address. Default is "localhost". "address": "localhost", // Port to attach to. "port": 5858, "sourceMaps": false >] >
João Marcelo Brito 3 Авг 2015 в 02:59
Я использовал Node Exec, конфигурация не требуется, создает файл, который вы в настоящее время завершаете или что когда-либо было выбрано, и выводит внутри VSCode.
С небольшой конфигурацией вы можете добавить Babel, чтобы делать некоторые транспиляции на лету.
dmo 10 Май 2017 в 21:37
Выполните следующие действия в коде VS. [выполняется в ОС Windows]
- Создать новый файл
- Напишите в нем коды javascript
- Сохраните файл как filename.js
- Перейдите в меню отладки
- Нажмите Начать отладку.
- или просто нажмите F5
CrackerKSR 24 Ноя 2019 в 20:03
Я столкнулся с этой проблемой, когда впервые начал использовать VS Code с расширением Code Runner
Вам нужно указать путь node.js в Настройках пользователя .
Вам необходимо указать Путь при его установке на вашем компьютере с Windows.
Для меня это было \»C:\\Program Files\\nodejs\\node.exe\»
Поскольку у меня есть пробел в имени каталога файлов
См. Это изображение ниже. Мне не удалось запустить код сначала , потому что я ошибся в имени пути
Надеюсь, это поможет вам.
И, конечно, ваш вопрос помог мне, так как я также пришел сюда, чтобы получить помощь по запуску JS в моем VS CODE
Legend 23 Янв 2018 в 05:55
Ну, чтобы просто запустить код и показать вывод на консоли, вы можете создать задачу и выполнить ее, в значительной степени, как упоминает @canerbalci.
Обратной стороной этого является то, что вы получите только результат и все.
Что мне действительно нравится делать, так это иметь возможность отлаживать код, скажем, я пытаюсь решить небольшой алгоритм или пробую новую функцию ES6, и я запускаю его, и в нем есть что-то подозрительное, я могу отлаживать его внутри VSC.
Итак, вместо того, чтобы создавать для него задачу, я изменил файл .vscode / launch.json в этом каталоге следующим образом:
< "version": "0.2.0", "configurations": [ < "name": "Launch", "type": "node", "request": "launch", "program": "$", "stopOnEntry": true, "args": [], "cwd": "$", "runtimeExecutable": null, "runtimeArgs": [ "--nolazy" ], "env": < "NODE_ENV": "development" >, "externalConsole": false, "sourceMaps": false, "outDir": null > ] >
Что это значит, так это то, что он запустит любой файл, в котором вы сейчас находитесь, в отладчике VSC. Он настроен на остановку при запуске.
Чтобы запустить его, нажмите клавишу F5 в файле, который вы хотите отладить.
lebobbi 13 Фев 2016 в 05:51
Ярлык для встроенного терминала: ctrl + ` , затем введите node .
В качестве альтернативы вы можете создать задачу. Это единственный код в моем tasks.json:
< // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "0.1.0", "command": "node", "isShellCommand": true, "args": ["$"], "showOutput": "always" >
Отсюда создайте ярлык. Это мой keybindings.json:
// Place your key bindings in this file to overwrite the defaults [ < "key": "cmd+r", "command": "workbench.action.tasks.runTask" >, < "key": "cmd+e", "command": "workbench.action.output.toggleOutput" >]
Это откроет «запустить» в Command Pallete, но вам все равно придется ввести или выбрать с помощью мыши задачу, которую вы хотите запустить, в данном случае node. Второй ярлык переключает панель вывода, ярлык для него уже есть, но эти клавиши расположены рядом друг с другом, и с ними легче работать.
Aliaksandr Sushkevich 17 Сен 2019 в 15:29
На мой взгляд, это самый быстрый способ для вас;
- Открытый интегрированный терминал в коде Visual Studio ( View > Integrated Terminal )
- тип ‘node filename.js’
- нажмите Ввод
примечание : требуется настройка узла. (если у вас домашний пивовар, просто введите на терминале ‘brew install node’)
примечание 2 : настоятельно рекомендуется использовать homebrew и node, если вы еще этого не сделали.
schrodigerscatcuriosity 7 Сен 2018 в 14:52
Есть гораздо более простой способ запустить JavaScript, настройка не требуется:
- Установите расширение Code Runner
- Откройте файл кода JavaScript в текстовом редакторе, затем используйте ярлык Control + Alt + N (или ⌃ Control + ⌥ Option + N в macOS), или нажмите F1 и затем выберите / введите Run Code , код будет запущен и вывод будет отображаться в окне вывода.
Кроме того, вы можете выбрать часть кода JavaScript и запустить фрагмент кода. Расширение также работает с несохраненными файлами, поэтому вы можете просто создать файл, изменить его на Javascript и быстро написать код (когда вам просто нужно что-то быстро попробовать). Очень удобно!
Lucio Paiva 8 Авг 2019 в 16:09
Я удивлен, что об этом еще не упоминалось:
Просто откройте соответствующий файл .js в VS Code, переключитесь на вкладку «Консоль отладки», нажмите кнопку отладки на левой панели навигации и нажмите значок запуска (кнопка воспроизведения)!
Требуется установка nodejs!
Как запустить код через Node.js
Когда запускаю код, через ctrl + alt + N мне вьіводится ошибка: Node.js не является используемой командой, что то вроде того, видел похожий вопрос, у меня потому что нет руського язіка просто вьіводится Node и куча символов (сели что у меня нет папки Node.js и я не знаю как не создать)Как запустить код? Помогите пожалуйста!
Отслеживать
3,563 8 8 золотых знаков 12 12 серебряных знаков 39 39 бронзовых знаков
задан 11 дек 2022 в 10:13
7 3 3 бронзовых знака
Кавычки неправильные. Это книжные кавычки.
11 дек 2022 в 10:14
js можно и в Visual Studio пилить, там все необходимое есть из коробки
11 дек 2022 в 10:16
И мне вьіводится ошибка — что ты делаешь, чтобы начала показываться ошибка? Какая ошибка показывается, полный текст?
11 дек 2022 в 10:31
попробуйте установить node js и перезапустить vs code
11 дек 2022 в 10:32
@Grundy запускаю код через ctrl + alt + N и мне вьіводится ошибка: Node.js не является используемой командой, что то вроде того, видел похожий вопрос, у меня потому что нет руського якзьіка просто вьіводится Node и куча символов
11 дек 2022 в 12:51
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
1. Скачать Node JS с официального ресурса — ссылка
2. Установить его «глобально» к себе на компьютер (как обычную программу).
Использование:
3. Открыть VSCode и нажать Ctrl + ~ (~ — где буква ё). Внизу редактора кода, откроется терминал. (Скорее всего «powershell» или «bush», в крайнем случае «cmd».
4. В поле терминала ввести команду «node -v» и нажать enter. Если терминал вернул версию Node JS (например v16.18.0) значит установлено все верно.
5. Теперь можно либо выполнять .js файлы либо писать код самому.
5.1 Писать код самому (Вводим в терминал node и enter) дальше как в обычном JavaScript, все написанное будет храниться в пределах сессии. Выйти из Node — Ctrl + C или .exit.
5.2 Выполнять .js файлы — в терминале пишем node и путь к файлу (относительно корня папки) например: node index.js
