Node.js
Node.js is a lightweight runtime environment for executing JavaScript outside the browser, for example, on the server or in the command line. IntelliJ IDEA integrates with Node.js providing assistance in configuring, editing, running, debugging, testing, profiling, and maintaining your applications.
If you need Node.js only as a local runtime for your application or for managing npm packages, running JavaScript linters, build tools, test frameworks, and so on, just install Node.js. If you follow the standard installation procedure, in most cases IntelliJ IDEA detects Node.js itself.
And even if you have no Node.js on your computer, you can install it when creating a new Node.js application in the Create New Project dialog , refer to Creating a new Node.js application below.
If you want to switch among several Node.js installations, they must be configured as local Node.js interpreters. In most cases, IntelliJ IDEA detects Node.js installations, configures them as interpreters automatically, and adds them to the list where you can select the relevant one.
To run a Node.js application remotely, configure it as a remote interpreter. For more information, refer to Node.js with Docker, Node.js via SSH, and Node.js with Vagrant .
Before you start
- Download and install Node.js.
- Make sure the JavaScript and TypeScript and Node.js required plugins are enabled on the Settings | Plugins page, tab Installed . For more information, refer to Managing plugins.
Switching between Node.js versions
With IntelliJ IDEA, you can have several installations of Node.js and switch between them while working on the same project.
- Press Control+Alt+S to open the IDE settings and then select Languages & Frameworks | Node.js .
- Select the required Node.js installation from the Node Interpreter list. If you followed the standard installation procedure, in most cases the required Node.js installation is on the list. If the installation is missing, click and configure it as a local interpreter manually.
Using a system Node.js version
With IntelliJ IDEA, you can set the default system node alias as your project’s Node.js version. After that, this version will be automatically used by all the tools that require Node.js and in all new run/debug configurations. In particular, this means that you will not have to update the settings for each tool if you install a new Node.js version and make it the default node alias in your system.
This functionality is especially helpful when you are using nvm.
- Press Control+Alt+S to open the IDE settings and then select Languages & Frameworks | Node.js .
- From the Node interpreter list, select node .
- Specify this new Node.js interpreter where applicable, for example, in your run/debug configurations or settings of specific tools.
Configuring a local Node.js interpreter
You may need to configure Node.js installation as an interpreter manually, for example, if Node.js is installed in a non-default location so IntelliJ IDEA does not detect it automatically.
- Press Control+Alt+S to open the IDE settings and then select Languages & Frameworks | Node.js .
- Click next to the Node Interpreter list.
- In the Node.js Interpreters dialog with a list of all the currently configured interpreters, click on the toolbar and select Add Local from the context menu and choose the installation of Node.js, then click OK . You return to the Node.js Interpreters dialog where the Node interpreter read-only field shows the path to the new interpreter.
- In the Package manager field, choose the package manager (npm, Yarn, or pnpm) for the current project. For more information, refer to Configuring a package manager for a project.
When you click OK , you return to the Node.js page where the Node interpreter field shows the new interpreter.
Using Node.js on Windows Subsystem for Linux
IntelliJ IDEA lets you run and debug Node.js applications using Node.js on Windows Subsystem for Linux. You can choose Node.js on WSL as the default interpreter for the current project or you can configure and use this Node.js version in a Node.js Run/Debug configuration.
Configure Node.js on WSL as the default project node interpreter
- In the Settings dialog ( Control+Alt+S ), go to Languages & Frameworks | Node.js .
- Click next to the Node Interpreter field, in the Node.js Interpreters dialog that opens, click , and then select Add WSL from the list.

- In the Add WSL Node Interpreter dialog that opens, select the Linux distribution you’re using and specify the path to Node.js.

Creating a Node.js application
If you have no application yet, you can generate an IntelliJ IDEA project with Node.js-specific structure from a template or create an empty IntelliJ IDEA project and configure Node.js in it as described in Starting with an existing Node.js application below.
You can also create a module from an existing Node.js application.
Create a new Node.js application

- Select File | New | Project from the main menu or click the New Project button on the Welcome screen.
- In the New Project dialog, select Express in the left-hand pane.
- In the right-hand pane, specify the project folder and the Node.js interpreter to use. For more information, refer to Configuring a local Node.js interpreter. Specify the express -generator in the express-generator field. It is recommended that you use npx that downloads and runs the generator. To do that, select npx —package express-generator express from the express -generator list. Alternatively, open the embedded Terminal ( Alt+F12 ) and type npm install —g express-generator and then select the downloaded generator from the express-generator list. Select the template language and the Style Sheet language to use.
- When you click Create , IntelliJ IDEA downloads the necessary dependencies and enables code completion for them as well as for the Node.js core APIs. For more information, refer to Configuring node_modules library and Configuring Node.js Core library. IntelliJ IDEA creates a run/debug configuration of the type Node.js with default settings and generates a basic Express-specific directory structure.
Create an empty IntelliJ IDEA project
- Select File | New | Project from the main menu or click the New Project button on the Welcome screen.
- In the New Project dialog, select New Project in the left-hand pane.
- In the right-hand pane, select JavaScript in the Language area and specify the project folder and name. To have a sample application generated, select the Add sample code checkbox.
Create a module from an existing Node.js app
- Download your application sources and store them on your computer.
- Go to File | New | Module from Existing Sources .
- In the dialog that opens, select the location of your application sources. Learn more from Modules.
Starting with an existing Node.js application
If you are going to continue developing an existing Node.js application, open it in IntelliJ IDEA, configure Node.js in it, and download the required dependencies.
Open the application sources that are already on your machine
- Click Open or Import on the Welcome screen or select File | Open from the main menu. In the dialog that opens, select the folder where your sources are stored.
Check out the application sources from your version control
- Click Get from VCS on the Welcome screen. Alternatively, select File | New | Project from Version Control or Git | Clone… from the main menu. Instead of Git in the main menu, you may see any other Version Control System that is associated with your project. For example, Mercurial or Perforce .
- In the dialog that opens, select your version control system from the list and specify the repository to check out the application sources from. For more information, refer to Check out a project (clone).
Configure Node.js in a project
- In the Settings dialog ( Control+Alt+S ), go to Languages & Frameworks | Node.js .
- In the Node Interpreter field, specify the default Node.js interpreter for the current project. IntelliJ IDEA automatically uses it every time you select the Project alias from Node Interpreter lists, for example, when creating run/debug configurations. Select a configured interpreter from the list or click and configure a new one in the dialog that opens as described in Configuring a local Node.js interpreter. If you select node , the system Node.js version is used.
- Select the Coding assistance for Node.js checkbox to configure the Node.js Core module sources as a JavaScript library and associate it with your project. As a result, IntelliJ IDEA provides code completion, reference resolution, validation, and debugging capabilities for fs , path , http , and other parts of Node.js that are compiled into the Node.js binary. When the configuration is completed, IntelliJ IDEA displays information about the currently configured version.
- If you need code completion for Node.js APIs only in some parts of your project, you can configure that using the Manage scopes link. In the Usage dialog that opens, click the relevant directories and for each of them select the configured Node.js Core library from the list. Learn more from Configuring the scope of a library.
Download the project dependencies
- In the embedded Terminal ( Alt+F12 ) , type: npm install
- Alternatively, select Run ‘npm install’ from the context menu of the package.json file in your project root.
Project security
When you open a project that was created outside IntelliJ IDEA and was imported into it, IntelliJ IDEA displays a dialog where you can decide how to handle this project with unfamiliar source code.

Select one of the following options:
- Preview in Safe Mode : in this case, IntelliJ IDEA opens the project in a preview mode. It means that you can browse the project’s sources but you cannot run tasks and script or run/debug your project. IntelliJ IDEA displays a notification on top of the editor area, and you can click the Trust project… link and load your project at any time.
- Trust Project : in this case, IntelliJ IDEA opens and loads a project. That means the project is initialized, project’s plugins are resolved, dependencies are added, and all IntelliJ IDEA features are available.
- Don’t Open : in this case, IntelliJ IDEA doesn’t open the project.
Projects created from the Welcome screen or via File | New | Project as described in are automatically considered trusted.
Running and debugging Node.js
WebStorm helps you run and debug your Node.js applications. You can debug applications that are started from WebStorm as well as attach to already running applications.
Before you start
- Make sure the Node.js and JavaScript Debugger required plugins are enabled on the Settings | Plugins page, tab Installed . For more information, refer to Managing plugins.
Running a Node.js application
WebStorm runs Node.js applications according to a run configuration of the type Node.js . WebStorm also uses this configuration to start the debugger together with Node.js applications.
Create a Node.js run/debug configuration
- Go to Run | Edit Configurations . Alternatively, select Edit Configurations from the list on the toolbar.
In the Edit Configurations dialog that opens, click the Add button () on the toolbar and select Node.js from the list. The Run/Debug Configuration: Node.js dialog opens. - Specify the Node.js interpreter to use. If you choose the Project alias, WebStorm will automatically use the project default interpreter from the Node interpreter field on the Node.js page . In most cases, WebStorm detects the project default interpreter and fills in the field itself. You can also choose another configured local or remote interpreter or click and configure a new one. For more information, refer to Configuring remote Node.js interpreters, Configuring a local Node.js interpreter, and Using Node.js on Windows Subsystem for Linux.
- In the JavaScript File field, specify the path to the main file of the application that starts it (for example, bin/www for Express applications).
- Optionally:
- Specify the Node parameters that customize the start of Node.js. For example, you may want to enable an experimental Node.js feature or pass another option. For more information, refer to the Node.js official website.
- In the Application parameters field, specify the Node.js-specific arguments to be passed to the application on start through the process.argv array.
- To open the application in the browser automatically, configure a before-launch task. Click to expand the Before launch area, click , and select Launch Web Browser from the list. In the dialog that opens, specify the URL of the application starting page, for example, localhost:3000 for Express applications, and the browser to use.

Run an application

- Create a run/debug configuration as described above or modify an existing one and click Run in the dialog.
- Alternatively, select the newly created run configuration from the list on the main toolbar and click . The application starts, and the Run tool window opens showing the application output.
If you are using a logging tool like morgan in your application and this tool writes logs to a file, you can see these logs in the Console tab of the Run tool window.
Manage logs when running a Node.js application
- Create a Node.js run/debug configuration as described above and go to the Logs tab.
- Click next to the Log files to be shown in console field which lists the available log files (if any).
- In the Edit Log Files Aliases dialog that opens, type the alias name to show in the list of log entries and specify the location of the log file. Select whether you want to show all files that this pattern covers or only the last one.
- Click OK to return to Node.js Run/Debug Configuration dialog, where the new log file is added to the list. Select the Is Active checkbox next to it. To skip the previous content, select the Skip Content checkbox.
- Optionally:
- To enable saving the Process Console output to a log file, select the Save console output to file checkbox and specify the file location.
- Choose when you want the Process Console shown.
Debugging a Node.js application
WebStorm makes it easier to debug Node.js applications. You can put breakpoints right in your JavaScript or TypeScript code so you no longer need any debugger and console.log() statements. You can do many things that will help you explore the code and understand where the bug is. In the Debug tool window, you can view the call stack and the variables in their current state, evaluate expressions in the editor, and step through the code.
You can initiate a debugging session in two ways:
- Start the debugger together with your application using a Node.js run/debug configuration.
- Attach the debugger to an already running application. In this case, your application is already running in the debug mode and WebStorm attaches to a running process. WebStorm recognizes —inspect , —inspect-brk , and now deprecated —debug flags so you can make any application accessible for debugging. To debug a running application, use an Attach to Node.js/Chrome configuration.
With WebStorm, you can also debug Node.js applications that are running in Vagrant boxes, in Docker containers, or on remote hosts accessible via various transfer protocols or via SSH.
Starting the debugger together with a Node.js application on your computer
- Set the breakpoints in the code where necessary.
- Create a Node.js run/debug configuration as described above. To open the application in the browser automatically, configure a before-launch task. Click to expand the Before launch area, click , and select Launch Web Browser from the list. In the dialog that opens, specify the URL of the application starting page, for example, localhost:3000 for Express applications, and the browser to use.
If necessary, WebStorm can generate a JavaScript Debug configuration and start it automatically together with the Node.js configuration as described in Debugging the server- and the client-side code. - Select the newly created Node.js configuration from the Select run/debug configuration list on the toolbar and click the Debug button () next to the list.
The Debug tool window opens. - Perform the steps that will trigger the execution of the code with the breakpoints. For example, navigate from the starting page of your application to another page in the browser.
- Switch to WebStorm, where the controls of the Debug tool window are now enabled. Proceed with the debugging session — step through the breakpoints, switch between frames, change values on-the-fly, examine a suspended program, evaluate expressions, and set watches.
Debugging a running Node.js application
With WebStorm, you can debug an already running application with the Chrome Debugging Protocol or with the V8 Debugging Protocol (also known as Legacy Protocol ).
In either case, a debugging session is initiated through an Attach to Node.js/Chrome configuration.
Start the debugger from the built-in Terminal or from the Run or Debug tool window
If an application was started with the —inspect or —inspect-brk flag, you can start a debugging session from the built-in Terminal , from the Run tool window, or from the Debug tool window.

- Run your application with an —inspect or —inspect-brk flag. You can do that in several ways, for example:
- Open the embedded Terminal ( Alt+F12 ) and, type: node —inspect-brk
- Launch a script from package.json or from the npm tool window. For more information, refer to Run and debug scripts. Depending on the action you select from the list, the output will be shown in the Run or in the Console tab of the Debug tool window.
- The Terminal , the Run tool window, or the Console tab of the Debug tool window shows an information message Debugger listening : , the default port is 9229 . To start debugging, hold Control+Shift and click the link. WebStorm starts a debugging session with an automatically generated Attach to Node.js/Chrome configuration. Alternatively, copy the port number from the Debugger listening : message and paste it later in the Attach to Node.js/Chrome configuration.
Debug with Chrome Debugging Protocol
Use this protocol to debug applications started with the —inspect or —inspect-brk flag. This flag is used with Node.js versions later than 6.3.

- Set the breakpoints as necessary.
- Select Run | Edit Configurations from the main menu, then click in the Edit Configuration dialog that opens, and select Attach to Node.js/Chrome from the list. The Run/Debug Configuration: Attach to Node.js/Chrome dialog opens.
- Specify the host where the target application is running and the port passed to —inspect or —inspect-brk when starting the Node.js process to connect to. Copy the port number from the information message Debugger listening : in the Terminal tool window or in the Run tool window that controls the running application. Make sure this port is different from the port on which the application is running. The default port is 9229. Optionally: specify the remote paths for the project folders in the Remote URLs of local files area. This is helpful if the root folder of the running application is different from the name of you WebStorm project root folder.
- In the Attach to area, select Chrome or Node.js > 6.3 started with —inspect .
- Select the newly created Attach to Node.js/Chrome configuration from the Select run/debug configuration list on the toolbar and click the Debug button () next to the list. The Debug tool window opens.
- Perform the actions that will trigger the code at the breakpoint. Control over the debugging session returns to WebStorm.
- Switch to WebStorm. In the Debug tool window, step through the breakpoints, switch between frames, change values on-the-fly, examine a suspended program, evaluate expressions, and set watches.
Debug with V8 Debugging Protocol
Use this protocol to debug applications started with the —debug flag. This flag is used with Node.js versions earlier than 8.
- Create an Attach to Node.js/Chrome run/debug configuration as described above and specify the host and the port passed to —debug . The default port is 9229.
- Make sure the application to debug was launched with the following parameters: —debug= . The default port is 5858 .
- Proceed as during a debugging session with Chrome Debugging Protocol.
Debugging a Node.js application that uses nodemon
The WebStorm built-in debugger can automatically reconnect to running Node.js processes. This lets you debug Node.js applications that use the nodemon utility, which automatically reloads your Node.js process when the code is updated.
To debug such application, you need to start it in the debug mode (with the —inspect or —inspect-brk flag) and then connect to it using the Attach to a Node.js/Chrome debug configuration with the Reconnect Automatically option on.
Install nodemon
- In the embedded Terminal ( Alt+F12 ) , type npm install —save-dev nodemon or yarn add nodemon —dev to install nodemon as a development dependency.
Start an application with nodemon in the debug mode
- Create and run the following npm debug script:
debug»: «nodemon —inspect
Debug an application
- Set the breakpoints in your code as necessary.
- Create a new Attach to a Node.js/Chrome configuration as described in Debugging a running Node.js application and select the Reconnect automatically checkbox.
Usually, you don’t need to change the port in the configuration 9229 because it’s the default port the debugger is listening on. But you can double-check what port is used in the message logged when you run the app in the debug mode. 
- Select the newly created Attach to Node.js/Chrome configuration from the Select run/debug configuration list on the toolbar and click the Debug button () next to the list. The debugger stops at the breakpoints that you put in your code in WebStorm. Now, every time you make any changes to the code and save them Control+S , nodemon will automatically reload the application, and the debugger will automatically re-attach to the restarted process.
# Как установить Node.js на Ubuntu 20.04
Node.js — одна из самых популярных программных платформ, предназначенная для трансляции JavaScript в машинный код. Node.js делает возможным использование Java для создания серверных приложений.
В этой инструкции мы расскажем о нескольких способах установки Node.js и опишем их преимущества. В конце инструкции напишем первое простое приложение, которое позволит проверить работоспособность установленного Node.js.
Нам понадобится подготовленный к работе сервер на Ubuntu 20.04.
# Установка Node.js
# Официальный репозиторий Ubuntu
Самый простой и быстрый способ установки Node.js — из официального репозитория Ubuntu. Синтаксис команд и последовательность действий в данном случае не отличаются от установки любого другого приложения на Ubuntu.
Сначала нужно обновить список пакетов apt :
sudo apt update sudo apt upgrade
Теперь можно переходить непосредственно к установке Node.js:
sudo apt install nodejs
Команда-установщик найдёт нужный пакет, уведомит нас о дисковом пространстве, которое будет занято, и произведёт установку Node.js.
Для установки дополнительных модулей (их называют пакетами) Node.js использует Node Package Manager — npm. В отличие от способов установки Node.js, которые будут описаны ниже, при установке Node.js из репозитория Ubuntu npm не устанавливается по умолчанию, его нужно установить отдельно:
sudo apt install npm
После завершения установки можно проверить версии установленных Node.js и npm:
node -v npm -v
Из официального репозитория Ubuntu устанавливается Node.js v.10.19.0 и соответствующая ей версия npm. Если вас устраивает эта версия, то можно переходить непосредственно к работе с Node.js, если нет, рассмотрите другие варианты установки.
# Официальный репозиторий Node.js
Для установки нужной версии Node.js из официального репозитория добавьте его в список репозиториев, используемых apt. Для этого воспользуйтесь командой curl в консоли:
curl -fsSL https://deb.nodesource.com/setup_ab.x | sudo -E bash -
При запуске команды замените ab на требуемую версию Node (12, 14, 16, 17).
Также можно установить последнюю текущую версию Node:
curl -fsSL https://deb.nodesource.com/setup_current.x | sudo -E bash -
Вы можете установить и версию с длительной поддержкой:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
На момент написания статьи это была Node.js v.16.x.
После выполнения команды curl обновите базы данных apt:
sudo apt update sudo apt upgrade
Теперь запустите установку Node.js:
sudo apt install nodejs
Программа установит выбранную версию Node.js и соответствующую ей npm. Проверить версии установленных программ можно командами:
node -v npm -v
# Node Version Manager
Менеджер версий Node.js (Node Version Manager, nvm) — самый гибкий из рассматриваемых нами инструментов. Он позволяет устанавливать любую версию Node.js.
Для начала установим сам nvm. Для этого зайдём на официальную страницу проекта на GitHub
(opens new window) и из файла README.md скопируем скрипт, запускающий установку nvm на нашем сервере:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
Перед запуском самого скрипта можно проверить его содержимое, запустив его без окончания | bash :
После того как скрипт отработает, получим для нашей учётной записи файл .bashrc :
source ~/.bashrc
Теперь nvm установлен и готов к работе, можно переходить непосредственно к установке Node.js.
Получим список доступных для установки версий:
nvm list-remote
Результатом выдачи станет длинный список. Выбираем версию, которую хотим установить, и используем команду install . Например:
nvm install v16.13.2
Выбранная версия Node.js и соответствующая версия npm будут автоматически установлены. Проверить версии установленных приложений можно командами:
node -v npm -v
# «Пакеты приложений» Джино
Для расположенных на Джино серверов доступен ещё один способ установки Node.js — из раздела меню «Пакеты приложений».
Откройте панель управления сервером, на который хотите установить Node.js, и в разделе меню Управление
Пакеты приложений выберите нужную версию Node.js.
Программа-установщик автоматически установит выбранную версию Node.js и соответствующую ей версию npm.
# Проверка работы Node.js
После установки и проверки версии в качестве «Контрольной проверки» напишем небольшое приложение, которое позволит проверить Node.js в действии.
В корневой папке создадим новый текстовый файл:
vim hello.js
Внутри него разместим простой код:
console.log(“Hello world!”);
Сохраним этот файл и запустим его с помощью node :
node hello.js
В результате в консоли будет выведено сообщение:
Hello world!
Если всё получилось, можно переходить к работе с Node.js.
# Переключение между версиями Node.js
Из-за отсутствия кроссверсионной поддержки часто приходится использовать несколько разных версий Node.js, установленных на одной машине. Для удобного переключения между ними также используется nvm .
nvm list
Мы увидим список всех установленных на сервере версий Node.js. Здесь будет выделена активная в данный момент версия. Также программа покажет список релизов Node.js с длительной поддержкой:
v16.13.2 -> v17.2.0 system default -> v17.2.0 node -> stable (-> v17.2.0) (default) stable -> 17.2 (-> v17.2.0) (default) iojs -> N/A (default) unstable -> N/A (default) lts/* -> lts/gallium (-> v16.13.2) lts/argon -> v4.9.1 (-> N/A) lts/boron -> v6.17.1 (-> N/A) lts/carbon -> v8.17.0 (-> N/A) lts/dubnium -> v10.24.1 (-> N/A) lts/erbium -> v12.22.10 (-> N/A) lts/fermium -> v14.19.0 (-> N/A) lts/gallium -> v16.13.2
Из этого списка можно выбрать и установить любой релиз. Например:
nvm install lts/carbon
Переключение между установленными версиями Node.js осуществляется с помощью команды use :
nvm use v16.13.2
После выполнения команды use можно проверить активную версию Node.js командой:
node -v
Также можно ввести такую команду:
nvm list
Теперь можно переходить к работе с Node.js.
© Джино, 2003–2022. «Джино» является зарегистрированным товарным знаком.
Лицензия на телематические услуги связи №150549 от 09.03.2017.
Number.isInteger()
Метод Number.isInteger() определяет, является ли переданное значение целым числом.
Интерактивный пример
Синтаксис
Number.isInteger(value)
Параметры
Значение, проверяемое на целочисленность.
Возвращаемое значение
Boolean сообщающий о том, является ли переданное значение целочисленным числом.
Описание
Если целевое значение является целым числом, возвращает true . Если значение NaN или Infinity , то возвращает false . Метод также возвращает true , если это вещественное число с точкой, которое может быть представлено в целочисленном виде.
Примеры
.isInteger(0); // true Number.isInteger(1); // true Number.isInteger(-100000); // true Number.isInteger(99999999999999999999999); // true Number.isInteger(0.1); // false Number.isInteger(Math.PI); // false Number.isInteger(NaN); // false Number.isInteger(Infinity); // false Number.isInteger(-Infinity); // false Number.isInteger("10"); // false Number.isInteger(true); // false Number.isInteger(false); // false Number.isInteger([1]); // false Number.isInteger(5.0); // true Number.isInteger(5.000000000000001); // false Number.isInteger(5.0000000000000001); // true
Полифил
.isInteger = Number.isInteger || function (value) return ( typeof value === "number" && isFinite(value) && Math.floor(value) === value ); >;
Спецификации
| Specification |
|---|
| ECMAScript Language Specification # sec-number.isinteger |
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
- Объект Number , которому принадлежит этот метод.
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 7 авг. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
