Как добавить node js в path windows

Have done a lot of googling, tried reinstalling node.js using the official installer, but my npm pathing still doesn't work. This doesn't work npm install foo I get an error message saying missing

Have done a lot of googling, tried reinstalling node.js using the official installer, but my npm pathing still doesn’t work.

This doesn’t work

npm install foo

I get an error message saying missing module npm-cli.js

2 hours of googling later I discovered a workaround
Instead of simply ‘npm‘ I type

node C:Program Filesnodejsnode_modulesnpmbinnpm-cli.js

But how can I correct my nodejs install so I can simply type ‘npm’ ?

Yar's user avatar

Yar

6,80011 gold badges46 silver badges66 bronze badges

asked Jan 9, 2015 at 15:36

Bachalo's user avatar

2

You need to Add C:Program Filesnodejs to your PATH environment variable. To do this follow these steps:

  1. Use the global Search Charm to search «Environment Variables»
  2. Click «Edit system environment variables»
  3. Click «Environment Variables» in the dialog.
  4. In the «System Variables» box, search for Path and edit it to include C:Program Filesnodejs. Make sure it is separated from any other paths by a ;.

You will have to restart any currently-opened command prompts before it will take effect.

James McCormack's user avatar

answered Jan 9, 2015 at 15:48

wjohnsto's user avatar

wjohnstowjohnsto

4,1831 gold badge14 silver badges19 bronze badges

7

get the path from npm:

npm config get prefix

and just as a future reference, this is the path I added in Windows 10:

C:Users{yourName}AppDataRoamingnpm


Update:

If you want to add it for all users just add the following path [by @glenn-lawrence from the comments]:

%AppData%npm

answered Aug 22, 2015 at 18:06

Yar's user avatar

YarYar

6,80011 gold badges46 silver badges66 bronze badges

5

I have used the cmdlet and navigate to the path you want to switch your npm files to. Type in npm root -g to see what the current path your npm is installed to. Next use npm config set prefix and your npm path will be changed to whatever directory you are currently on.

Constantin's user avatar

Constantin

8,58112 gold badges77 silver badges122 bronze badges

answered Jul 27, 2017 at 1:34

Martez C's user avatar

Martez CMartez C

2012 silver badges2 bronze badges

1

Try this one dude if you’re using windows:

1.) Search environment variables at your start menu’s search box.
2.) Click it then go to Environment Variables...
3.) Click PATH, click Edit
4.) Click New and try to copy and paste this: C:Program Filesnodejsnode_modulesnpmbin

If you got an error. Do the number 4.) Click New, then browse the bin folder

  • You may also Visit this link for more info.

answered Oct 28, 2016 at 12:20

Go to control panel -> System -> Advanced System Settings then environment variables.

From here find the path variable, Go to the end of the line and paste «C:Program Filesnodejsnode_modulesnpmbin» (change the path to the directory to where ever you installed it e.g. if you specifically installed it anywhere change it)

answered Jan 9, 2015 at 15:52

Dennington-bear's user avatar

Dennington-bearDennington-bear

1,6944 gold badges19 silver badges44 bronze badges

Edit the System environment variables, and enter following path:

C:Program Filesnodejsnode.exe;

C:Users{yourName}AppDataRoamingnpm

mate00's user avatar

mate00

2,5995 gold badges25 silver badges34 bronze badges

answered Jul 25, 2019 at 2:50

willey's user avatar

willeywilley

911 silver badge2 bronze badges

Installed Node Version Manager (NVM) for Windows: https://github.com/coreybutler/nvm-windows

I’m using Windows 10 — 64 bit so I run…
Commands:

  • nvm arch 64 (to make default the 64 bit executable)
  • nvm list (to list all available node versions)
  • nvm install 8.0.0 (to download node version 8.0.0 — you can pick any)
  • nvm use 8.0.0 (to use that specific version)

In my case I had to just switch to version 8.5.0 and then switch back again to 8.0.0 and it was fixed.
Apparently NVM sets the PATH variables whenever you do that switch.

answered Sep 22, 2017 at 14:29

Altin's user avatar

AltinAltin

2,1353 gold badges25 silver badges46 bronze badges

1

You can follow the following steps:

  • Search environment variables from start menu’s search box.
  • Click it then go to Environment Variables
  • Click PATH
  • click Edit
  • Click New and try to copy and paste your path for ‘bin‘ folder [find where you installed the node] for example according to my machine ‘C:Program Filesnodejsnode_modulesnpmbin

If you got any error. try the another step:

  • Click New, then browse for the ‘bin‘ folder

Community's user avatar

answered Jan 6, 2020 at 9:31

Md Wahid's user avatar

Md WahidMd Wahid

4505 silver badges12 bronze badges

2

If after installing your npm successfully, and you want to install VueJS then this is what you should do

after running the following command (as Admin)

npm install --global vue-cli

It will place the vue.cmd in the following directory
C:UsersYourUserNameAppDataRoamingnpm

you will see this in your directory.

Now to use vue as a command in cmd. Open the cmd as admin and run the following command.

setx /M path "%path%;%appdata%npm"

Now restart the cmd and run the vue again. It should work just fine, and then you can begin to develop with VueJS.

I hope this helps.

answered Dec 19, 2019 at 22:30

Premium Ayodele's user avatar

Premium AyodelePremium Ayodele

3972 gold badges6 silver badges11 bronze badges

0

This worked for me:
1. npm root -g (to see the current npm is installed)
2. npm config set prefix (to change the path)

answered Dec 19, 2017 at 9:11

marty's user avatar

martymarty

492 bronze badges

I did this in Windows 10,

  1. Search for Environment Variables in the Windows search
  2. «Edit the System environment variables» option will be popped in the result
  3. Open that, select the «Path» and click on edit, then click «New» add your nodeJS Bin path i.e in my machine its installed in c:programfilesnodejsnode_modulesnpmbin
  4. Once you added click «Ok» then close

Now you can write your command in prompt or powershell.

If you using WIndows 10, go for powershell its a rich UI

Szabolcs Páll's user avatar

answered Apr 1, 2019 at 6:16

Mohan Raj Raja's user avatar

change the path for nodejs in environment varibale.

setting environment variable

Machavity's user avatar

Machavity

30.4k27 gold badges90 silver badges100 bronze badges

answered Oct 21, 2018 at 2:21

brean's user avatar

breanbrean

7572 gold badges9 silver badges17 bronze badges

add Environment Path to

C:Program Filesnodejsnode.exe;C:Users[your username]AppDataRoamingnpm

phantomraa's user avatar

phantomraa

1,5771 gold badge18 silver badges25 bronze badges

answered Apr 15, 2019 at 11:01

Thai Mozhi Kalvi's user avatar

steps 1
in the user variable and system variable

  C:Program Filesnodejs

then check both node -v
and the npm -v
then try to update the the npm i -g npm

answered Mar 9, 2020 at 10:19

Mohammed Al-Reai's user avatar

I’ve had this issue in 2 computers in my house using Windows 10 each.
The problem began when i had to change few Environmental variables for projects that I’ve been working on Visual studio 2017 etc.
After few months coming back to using node js and npm I had this issue again and non of the solutions above helped.
I saw Sean’s comment on Yar’s solution and i mixed both solutions:
1) at the environmental variables window i had one extra variable that held this value: %APPDATA%npm. I deleted it and the problem dissapeared!

answered Feb 20, 2018 at 18:58

S.vaysrub's user avatar

If you can’t work with npm packages, you propably has bad config with npm install packages, you try this:

Run the following command in your terminal to revert back to the default registry

npm config set registry https://registry.npmjs.org/

https://docs.npmjs.com/misc/config#registry

RobC's user avatar

RobC

21.8k20 gold badges66 silver badges75 bronze badges

answered Oct 13, 2019 at 13:50

When you’re on Windows but running VS Code in Windows Subsystem for Linux like this

linux@user: /home$ code .

you actually want to install NodeJs on Linux with

linux@user: /home$ sudo apt install nodejs

Installing NodeJs on Windows, modifying PATH and restarting will get you no results.

answered Apr 22, 2020 at 19:49

a'''s user avatar

2,2522 gold badges22 silver badges34 bronze badges

If, like me, you have MSYS_NO_PATHCONV = 1 configured as a user variable for Git Bash, this issue will be triggered. To workaround, you can either remove this variable or use a different shell (PowerShell) for npm.

answered Feb 16, 2021 at 9:35

Alex Ward's user avatar

I did Node repair with the .msi file and everything worked well.

Dharman's user avatar

Dharman

29.3k21 gold badges79 silver badges131 bronze badges

answered Apr 24, 2021 at 13:19

Jimmy's user avatar

JimmyJimmy

912 silver badges5 bronze badges

I may be a total noob but I had no clue I had to install npm-cli first. I had just assumed I already had it.

npm install --global vue-cli

answered Jul 11, 2019 at 2:58

ninjasense's user avatar

ninjasenseninjasense

13.7k18 gold badges74 silver badges92 bronze badges

2

Содержание

  1. 3. Установка и запуск
  2. http://nodejs.org
  3. Исправление пути npm в Windows 8 и 10
  4. Обновить:
  5. Node не распознается как внутренняя или внешняя команда, а находится в PATH
  6. ОТВЕТЫ
  7. Ответ 1
  8. Ответ 2
  9. Ответ 3
  10. Ответ 4
  11. Ответ 5
  12. Ответ 6
  13. Ответ 7
  14. Возможное решение
  15. Ответ 8
  16. Ответ 9
  17. Ответ 10
  18. Установка Node.js в Windows
  19. Установка nvm-windows, Node.js и npm
  20. Альтернативные диспетчеры версий
  21. Установка Visual Studio Code
  22. Альтернативные редакторы кода
  23. Установка GIT
  24. node.js для Java-разработчиков: первые шаги
  25. Установка и настройка
  26. Первые шаги
  27. Работа с npm
  28. Работа в IntelliJ IDEA
  29. Модульность в node.js
  30. Тестирование

3. Установка и запуск

http://nodejs.org

Ну что, время завязывать со всякой нудной теорией и переходить к практике. Сейчас мы посмотрим как установить Node.JS, как на нем выполнять скрипты и немножко залезем в документацию. Для этого я первым делом зайду на сайт http://nodejs.org. Здесь есть такая большая кнопка, которая, как правило, позволяет скачать пакет наиболее подходящий для вашей ОС. Вначале посмотрим, что с Mac OS. С Mac OS все просто, мы жмем на кнопку, скачиваем «node-v4.4.7.pkg», запускаем его, все подтверждаем, все очень очевидно, мы не будем это рассматривать, ошибиться тут не возможно.

Следующее это Linux. С Linux все чуть сложнее, потому что в Linux обычно есть различные пакеты, но в пакетах не самая новая версия, а при работе с Node.JS лучше использовать последние версии, если нет каких-то особых причин так не делать. Так что если вы ставите из пакета, то убедитесь, что версия именно последняя. Если у вас пакет устарел, то Node.JS замечательно компилируется из исходников. Для этого можно загуглить «nodejs linux» в первых пяти ссылках обязательно будет инструкция по установке. Можете загуглить установку под какую то определенную систему например «node.js debian» и вы тоже находите инструкцию на первой же странице. Если вы пользуетесь Linux, то этот процесс не составит для вас особого труда.

Ну и наконец Windows. нажимаем на кнопку и скачиваем «node-v4.4.7-x64.msi» —

Screenshot 3 1

после того как он скачался, запускаю и соглашаюсь со всем, что предложит операционная система, все по умолчанию. Отлично Node.JS установился. Установился он в C:Program Filesnodejs и тут есть как файл node.exe так и npm.cmd. NPM это пакетный менеджер мы рассмотрим его немножко позже.

Screenshott 3 2

Node.JS когда ставится прописывает себя в переменную PATH. Чтобы в этом удостовериться можете проделать следующее — в Windows 10 нажимаете правой кнопкой мыши на значок «windows», который некогда был «пуск». В появившемся окне выбираем «система»

Screenshot 3 3далее жмем на «Дополнительные параметры системы», потом «переменные среды.

Screenshot 3 4Screenshot 3 5

Перед нами появилось окно «переменные среды» в котором нас интересует записи в среду PATH. Причем не важно для всех пользователей или для вашего пользователя (в нижнем окне или в верхнем) главное, что присутствуют записи «C:UsersASUSAppDataRoamingnpm» и «C:Program Filesnodejs». Теперь проверим работает ли Node.JS в принципе. Для этого в любой папке или на «Рабочем столе» при зажатой клавише «Shift» нажимаем правую кнопку мыши и выбираем «Открыть окно команд» такой трюк позволяет нам открыть консоль с прописанным путем в ту папку в которой мы нажали правую кнопку мыши. Другой способ открыть консоль через меню «пуск». Нажимаем правой кнопкой мыши меню «пуск», выбираем «Командная строка».

Screenshot 3 8

Screenshot 3 9

Итак мы запустили консоль. Вводим команду «node» и у нас появляется приглашение ввести javascript выражение. Это так называемый режим «repl» когда можно вводить javascript выражения и они выполняются.

Screenshot 3 10

Дважды нажав сочетание клавиш «Ctrl + c» мы выходим из этого режима. Вообще этот режим используется достаточно редко, здесь мы его используем просто, чтоб проверить, что установка прошла успешно. Конечно же такой запуск должен работать не только в «Windows», а и из любой операционной системы.

Источник

Исправление пути npm в Windows 8 и 10

Много гуглили, пробовали переустановить node.js с помощью официального установщика, но мой путь npm по-прежнему не работает.

Я получаю сообщение об ошибке, в котором говорится, что отсутствует модуль npm-cli.js

Через 2 часа поисков в Google я обнаружил обходной путь.
Вместо того, чтобы просто набирать npm

Но как мне исправить установку nodejs, чтобы я мог просто набрать npm?

Вам нужно добавить C:Program Filesnodejs в переменную среды PATH. Для этого выполните следующие действия:

Вам придется перезапустить все открытые в данный момент командные строки, прежде чем они вступят в силу.

получить путь из npm:

npm config get prefix

и просто в качестве справки на будущее, это путь, который я добавил в Windows 10:

Обновить:

Если вы хотите добавить его для всех пользователей, просто добавьте следующий путь [от @ glenn-lawrence из комментариев]:

Отсюда найдите переменную пути, перейдите в конец строки и вставьте «C: Program Files nodejs node_modules npm bin» (измените путь к каталогу, в котором вы его установили, например, если вы специально установили его где угодно меняй это)

Если вы используете Windows, попробуйте этого, чувак:

Если вы получили ошибку. Сделайте номер 4.) Нажмите New, затем просмотрите папку bin

Установленный диспетчер версий узлов (NVM) для Windows: https://github.com/coreybutler/nvm-windows

В моем случае мне пришлось просто переключиться на версию 8.5.0, а затем снова переключиться на 8.0.0, и это было исправлено. Очевидно, NVM устанавливает переменные PATH всякий раз, когда вы делаете этот переключатель.

Источник

Node не распознается как внутренняя или внешняя команда, а находится в PATH

Хотя я следую советам:

Я следил за предложениями в SO, добавляя переменную к переменным среды и отображая Ok в пути:

Следующая строка не будет выполнена

Но если я перейду в список папок в Path, то он будет работать нормально.

ОТВЕТЫ

Ответ 1

Каталог nodejs в вашем PATH не распознается, потому что перед точкой с запятой существует пробел, поэтому Windows ищет каталог с пробелом в конце имени, которого не существует.

Ответ 2

Ошибка: ‘node’ не распознается как внутренняя или внешняя команда

Проблема может заключаться в том, что node не установлен на компьютере, на котором работает приложение.

Затем установите его и установите переменную среды для nodejs.

Еще одной причиной может быть путь nodejs, который не задан в переменной среды.

Обратите внимание на следующее: открыть панель управления → Система и безопасность → Система → Расширенные настройки системы → Переменные среды → Путь

путь nodejs должен быть доступен здесь. Если недоступно, добавьте следующее:

C:Program Files (x86)nodejs ИЛИ C:Program Filesnodejs

Теперь перезапустите приложение, и ошибка была решена.

Ответ 3

Слэш послеnodejsработал у меня

Ответ 4

Обычно переменные среды не действуют до тех пор, пока система Restart.

Я предлагаю System Restart для всех тех, кто сталкивается с той же проблемой при выполнении чистой установки.

Это сработало для меня.

Ответ 5

Ответ 6

В Windows вам необходимо установить путь к папке node.js в системные переменные или пользовательские переменные.

1) откройте Панель управления → Система и безопасность → Система → Расширенные настройки системы → Переменные среды

3) Перезагрузите среду IDE или компьютер.

Полезно также добавить пути «npm» и «Git» как переменные, разделенные точкой с запятой.

Ответ 7

Если вы проверили свой PATH и уверены, что путь для node добавлен правильно, то вы, вероятно, столкнетесь с проблемой во время выполнения команд node OR npm с CLI, отличным от интерфейс командной строки по умолчанию для операционной системы (например, Git bash в Windows).

Возможное решение

Попробуйте запустить node с терминалом по умолчанию для вашей ОС.

Ответ 8

Я столкнулся с этой проблемой даже после добавления node.exe в PATH. Я не смог запустить команду node в случайных местах без запуска командной строки в качестве администратора.

Решение этой проблемы заключается в том, что вы должны предоставить полный доступ к этому файлу node.exe для разных типов пользователей. откройте свойства node.exe, перейдите на вкладки безопасности, проверьте все параметры безопасности для пользователя на локальном компьютере.

после этого вы сможете получить доступ к node.exe файлу из любого места.

Ответ 9

И следующее решение:

Ответ 10

Это так же просто, как добавить расположение nodejs ( C:Program Files (x86)nodejs ) в вашу переменную PATH и перезапустить приложение с помощью «Запуск от имени администратора».

Источник

Установка Node.js в Windows

Если вы не занимались разработкой с помощью Node.js и хотите быстро начать работу, установите Node.js непосредственно в Windows, выполнив указанные ниже действия.

Если вы используете Node.js профессионально и вам нужно оптимизировать скорость и производительность, обеспечить совместимость системных вызовов, выполнять контейнеры Docker, которые используют рабочие области Linux, и не нужно использовать скрипты сборки Linux и Windows или вы просто предпочитаете использовать командную строку Bash, установите Node.js в подсистеме Windows для Linux (точнее, в WSL 2).

Установка nvm-windows, Node.js и npm

Наряду с возможностью выбора системы для разработки (Windows или WSL) при установке Node.js доступны и другие возможности. Мы рекомендуем использовать диспетчер версий, так как версии меняются достаточно быстро. Вероятно, вам придется переключаться между несколькими версиями Node.js в зависимости от потребностей для различных проектов, над которыми вы работаете. Диспетчер версий Node Version Manager, чаще называемый nvm, является наиболее популярным средством установки нескольких версий Node.js, но он доступен только для Mac и Linux и не поддерживается в Windows. Вместо этого выполним шаги ниже, чтобы установить nvm-windows, а затем используем его для установки Node.js и диспетчера пакетов Node Package Manager (npm). Существуют также альтернативные диспетчеры версий, которые описаны в следующем разделе.

Рекомендуем всегда удалять любые имеющиеся установки Node.js или npm из операционной системы перед установкой диспетчера версий, так как эти установки могут создавать необычные и запутанные конфликты. Сюда относится удаление всех существующих каталогов установки Node.js (например, C:Program Filesnodejs), которые могут остаться. Созданная символьная ссылка NVM не будет перезаписывать существующий (даже пустой) каталог установки. Справку по полному удалению предыдущих установок см. здесь.

Откройте репозиторий windows-nvm в Интернет-браузере и щелкните ссылку Загрузить сейчас.

Скачайте последний выпуск файла nvm-setup.zip.

После скачивания откройте ZIP-файл, а затем запустите файл nvm-setup.exe.

Мастер установки Setup-NVM-for-Windows поможет выполнить все этапы установки, в том числе выбрать каталог, в котором будут установлены репозиторий nvm-windows и Node.js.

install nvm for windows wizard

Установка завершится. откройте PowerShell и попробуйте использовать windows-nvm, чтобы просмотреть список установленных версий Node (на этом этапе их еще не должно быть): nvm ls

windows nvm powershell no node

windows nvm list

windows nvm node installs

После установки требуемых версий Node.js выберите нужную версию, введя nvm use (замените нужным номером, например nvm use 12.9.0 ).

Альтернативные диспетчеры версий

Несмотря на то что windows-nvm сейчас является самым популярным менеджером версий для Node, есть несколько альтернативных вариантов:

nvs (Node Version Switcher) — это кроссплатформенный вариант nvm с возможностью интеграции с VS Code.

Volta — это новый диспетчер версий, созданный командой LinkedIn. Заявлено, что он отличается увеличенной скоростью и межплатформенной поддержкой.

Чтобы установить Volta в качестве диспетчера версий (вместо windows-nvm), перейдите в раздел Установка Windows руководства Начало работы, затем скачайте и запустите установщик Windows, следуя инструкциям.

Перед установкой Volta необходимо убедиться, что на компьютере с Windows включен режим разработчика.

Дополнительные сведения об использовании Volta для установки нескольких версий Node.js в Windows см. в документации по работе с Volta.

Установка Visual Studio Code

Для разработки с помощью Node.js в Windows рекомендуем установить Visual Studio Code, а также пакет расширений Node.js. Установите их все или выберите наиболее полезные для вас.

Чтобы установить пакет расширений Node.js, сделайте следующее:

К дополнительным рекомендуемым расширениям относятся следующие:

Альтернативные редакторы кода

Если вы предпочитаете использовать редактор кода или интегрированную среду разработки, отличные от Visual Studio Code, для среды разработки Node.js также подходят следующие варианты:

Установка GIT

Если вы планируете работать совместно с другими пользователями или размещать проект на сайте с открытым исходным кодом (например, GitHub), примите во внимание, что VS Code поддерживает управление версиями с помощью Git. Вкладка системы управления версиями в VS Code отслеживает все изменения и содержит общие команды Git (добавление, фиксация, принудительная отправка, извлечение) прямо в пользовательском интерфейсе. Сначала необходимо установить Git для включения панели управления версиями.

Скачайте и установите Git для Windows с веб-сайта git-scm.

В комплект входит мастер установки, который задает вам ряд вопросов о параметрах установки Git. Рекомендуется использовать все параметры по умолчанию, если у вас нет конкретной причины изменить какой-либо из них.

Если вы никогда не использовали Git, обратитесь к руководствам по GitHub. Они помогут вам приступить к работе.

Источник

node.js для Java-разработчиков: первые шаги

f91c5cfe26e84272803ac6468c3942d7

У опытного программиста, сталкивающегося с новой технологией для решения конкретной прикладной задачи, сразу возникает множество практических вопросов. Как правильно установить платформу? Где и что будет лежать после установки? Как создать каркас проекта, как он будет структурирован? Как разбивать код на модули? Как добавить библиотеку в проект? Где вообще взять готовую библиотеку, которая делает то, что нужно? Как и в чём отлаживать код? Как написать модульный тест?

Ответы на эти вопросы можно при желании легко найти в сети, но придётся перечитать дюжину статей, и на каждый вопрос ответов будет, скорее всего, несколько. Некоторое время назад мне понадобилось написать небольшой туториал по node.js, который бы позволил быстро запустить разработку и познакомить новых программистов в проекте с этой технологией. Рассчитан он на опытных Java-разработчиков, которые и язык JavaScript хорошо знают, но node.js как платформа для бэкэнда для них в новинку.

Думаю, что данная статья будет полезна не только разработчикам из мира Java, но и всем, кто начинает работу с платформой node.js.

ec2eb4735a834eb78bf82b00c21cde99

Установка и настройка

Установка node и npm
Windows

Установка node.js под Windows производится с помощью msi-инсталлятора. Для его загрузки нужно перейти на сайт https://nodejs.org и щёлкнуть «Install». После скачивания инсталлятора (файл с именем вида node-v0.12.4-install.msi) необходимо запустить его и следовать инструкциям по установке.

image loader

По умолчанию под Windows node.js устанавливается в папку c:Program Filesnodejs. Также по умолчанию устанавливаются все компоненты (собственно node.js, пакетный менеджер npm, ссылка на документацию; кроме того, путь к node и npm прописывается в переменную среды PATH). Желательно убедиться, что все компоненты установки выбраны.

image loader

В OS X проще всего установить node через менеджер пакетов brew. Для этого необходимо выполнить команду:

Node установится в папку /usr/local/Cellar/ /node с постоянным симлинком /usr/local/opt/node/.

Ubuntu (x64)

Для установки последней ветки (0.12) лучше скачать дистрибутив с сайта:

Дистрибутив распакуется в папку /usr/local в подпапки bin, include, lib и share.

Проверка установки
Установка плагина в IntelliJ IDEA

Запустим IntelliJ IDEA, зайдём в настройки.

image loader

Найдём раздел Plugins и щёлкнем «Install JetBrains Plugin. »

image loader

Найдём в списке плагин NodeJS, щёлкнем по кнопке «Install Plugin». По окончании загрузки кнопка превратится в «Restart IntelliJ IDEA» — щёлкнем её для перезагрузки среды.

image loader

image loader

В разделе «Sources of node.js Core Modules» щёлкнем кнопку «Configure». В появившемся окне выберем «Download from the Internet» и щёлкнем «Configure», при этом скачаются и проиндексируются исходники node.js. Это позволит просматривать исходники при разработке.

image loader

В разделе packages отображаются глобально установленные пакеты (см. раздел «Глобальные пакеты»). В этом окне можно добавлять, удалять и обновлять эти пакеты. Если рядом с именем пакета отображается синяя стрелочка, значит, доступно обновление. Глобально лучше устанавливать только пакеты-утилиты.

Первые шаги

Пишем «Hello World»

Создадим файл app.js, который формирует и выводит соответствующую строчку в консоль:

Запустим его командой:

Используем REPL

Запустив команду node без аргументов, можно попасть в REPL-цикл, аналогичный браузерной JS-консоли. В нём можно выполнять и проверять фрагменты кода:

Каждая выполненная строчка имеет возвращаемый результат, который также выводится в консоль. Функция console.log() не возвращает результата, поэтому после её вызова в консоли вывелось «undefined».

В REPL-консоли работает автодополнение по нажатию клавиши Tab. Например, если написать «console.» и нажать Tab, то отобразится список атрибутов и функций объекта console.

Для выхода из консоли можно нажать Ctrl+D.

Работа с npm

Инициализация проекта

Для инициализации проекта выполним в каталоге будущего проекта команду npm init и введём необходимые данные в интерактивном режиме (можно просто нажимать Enter, так как предлагаются внятные настройки по умолчанию):

По окончании выполнения утилиты в текущем каталоге будет создан файл package.json, описывающий конфигурацию проекта. В нём же будет храниться информация о зависимостях проекта.

Добавление пакетов-зависимостей в проект

После выполнения этой команды обнаружим, что в текущем каталоге появилась папка node_modulesopen, а в файле package.json добавилась запись:

Запись о зависимости можно добавить в файл package.json и вручную, но после этого необходимо выполнить npm install, чтобы загрузить указанную зависимость в каталог node_modules.

Глобальные пакеты

Пакеты можно устанавливать как в каталог проекта, так и глобально, тогда они будут видны для всех проектов. Как правило, глобально устанавливаются только пакеты, являющиеся утилитами, например, утилита управления зависимостями bower, сборщики gulp и grunt, генератор проектов на Express express-generator, и т.д.

Глобальные пакеты устанавливаются:

Работа в IntelliJ IDEA

Открытие проекта

Чтобы открыть проект на node.js, достаточно открыть папку, содержащую package.json.

image loader

Настройка конфигурации запуска

image loader

Заполним поля Name и JavaScript File:

image loader

Теперь можно запускать скрипт в обычном режиме и в режиме отладки с помощью соответствующих кнопок на панели инструментов:

image loader

Отладка

Для отладки необходимо запустить созданную конфигурацию в режиме Debug. При этом можно ставить брейкпойнты на строки, «шагать» по строкам, смотреть содержимое стека вызовов, значения переменных в текущем контексте и делать всё прочее, что ожидается от отладочного режима.

image loader

Модульность в node.js

В Java единицами модульности являются пакеты и классы. Единицей модульности в node.js является файл. Чтобы сделать импорт одного модуля в другой, используется модуль-локальная (т.е. неявно определённая в каждом модуле) функция require(). Стандартные модули или пакеты, установленные в node_modules, можно импортировать по простому имени:

В переменную http будет помещён объект, который был экспортирован модулем http.

Всё, что объявлено в файле модуля, видно только внутри него — за исключением того, что мы явно экспортируем. Например, в отличие от JavaScript в браузере, область видимости переменной, объявленной на верхнем уровне, ограничена тем модулем, в котором она объявлена:

Переменная enterprise будет видна только внутри модуля mymodule.js.

Чтобы экспортировать что-либо из модуля, можно использовать доступный в любом модуле атрибут module.exports, который по умолчанию содержит в себе пустой объект. Можно также использовать сокращённую ссылку на него — модуль-локальную переменную exports. Функция require(), которой передано имя нашего модуля, будет возвращать то, что мы поместили в module.exports. Соответственно, если мы поместим туда такой объект:

То именно его вернёт функция require, будучи вызванной в другом модуле:

Полученный объект mymodule — это тот же самый объект с функцией fun, который был присвоен атрибуту module.exports в нашем модуле.

Однако подобным способом сделать экспорт не получится:

Это связано с тем, что из модуля всегда экспортируется атрибут module.exports. Заменив сокращённую ссылку exports на другой объект, мы не изменили этот атрибут. Сокращённая ссылка exports может быть использована только для экспорта каких-то отдельных функций или атрибутов:

Тестирование

Mocha

Для добавления модульного тестирования в проект лучше всего начать с фреймворка Mocha. Устанавливается он как глобальный npm-модуль:

Протестируем модуль с простейшей функцией:

Тесты mocha по умолчанию размещаются в подпапке test:

Первый аргумент функции describe — это человекочитаемое описание поведения тестируемой функции или модуля, которое будет выводиться в консоль при прогоне тестов. Здесь желательно придерживаться некоторых структурных соглашений — например, в первом describe указывается имя модуля, во вложенном — имя тестируемой функции. Запустим mocha и убедимся, что тест нашей функции проходит:

Использование Mocha в IntelliJ IDEA

image loader

В окне настройки конфигурации запуска укажем название этой конфигурации (Name), а также путь к папке с тестами (Test directory). Сохраним конфигурацию.

image loader

Изменим код функции так, чтобы он не проходил, и выполним (Run) конфигурацию запуска Mocha.

image loader

Теперь щёлкнем кнопку Toggle auto-test в появившейся панели. Эта кнопка включает режим автоматического прогона тестов при изменении исходников.

image loader

Исправим код функции, при этом Mocha автоматически прогонит тест и покажет, что теперь всё хорошо:

Источник

Node.js is a javascript runtime environment. It encapsulates the google Chrome V8 engine and optimizes some special use cases and provides an alternative API that makes the V8 engine execute better in a none browser environment. It is a single thread, event-driven, and none block IO framework, all these characters make it runs very fast and efficiently. This article will tell you how to install it in Windows and how to write the hello world example use it.

1. Install Node.js In Windows.

1.1 Install Node With Windows Installer.

  1. Go to the Node.js download page to download the Windows version to your local PC.
  2. Double click the installer file to start the installation. The process is simple and clear, just click the Next button until finish. Please remember the Node.js installed directory during the installation.

1.2 Install Node With Windows Binary.

Besides using the windows installer, you can also install the Node.JS with a binary file which is compressed in a zip format file.

  1. Download it from https://nodejs.org/dist/v8.10.0/node-v8.10.0-win-x64.zip.
  2. Then unzip it to a local directory.
  3. Add the directory ( C:WorkSpacedev2qa.comToolnode-v7.10.1-win-x64 ) to system variable Path value.
  4. Open dos command window, run node -v to verify that the installation is successful.

2. Verify Node.js Installation.

2.1 Verify Node.JS.

Now Node.js has been installed in windows, you can run the below command in a dos window to test whether it is installed successfully or not.

C:UsersJerry>node --version
v14.16.0

If the output is the correct Node.js version that you installed, that means you installed Node.JS successfully.

If you meet errors such as ‘node is not recognized as an internal or external command, operable program or batch file‘, that means node.exe can not be found in the executable program path. You just need to add the Node.js installation directory( C:Program Filesnodejs ) in the Path system variable value as below.

  1. Open Windows file explorer.
  2. Right-click your computer icon in the left panel.
  3. Click Properties in the popup menu list.
  4. Click Advanced system settings in the opened window.
  5. Click the Environment Variables button in the System Properties window.
  6. In the System variables area, find the Path variable and add the Node.js installation directory path at the end of the Path variable value. Do not forget to add a semicolon ( ; ) before the directory value.
  7. After the above settings, open a new dos terminal and run the command path in it, you should see the Node.js installation directory in the value.

2.2 Verify NPM.

NPM is the abbreviation of node package manager, it is installed during Node.js installation also. Run below command in a dos terminal to check it’s installation status. If output the correct version number means it is installed correctly.

C:UsersJerry>npm --version
6.14.11

3. Write And Execute The First Node.js Script.

Now you can write your first Node.js script file. I recommend you use sublime text as the JavaScript editor, it is simple and easy to use. You can also use Eclipse, Android Studio, etc that you are familiar with. Just write below JavaScript code in a file saved as hello_node.js.

console.log('Hello Node.js!');

Cd to the js file saved directory and execute node hello_node.js in dos terminal, then you can see Hello Node.js! is printed.

4. Execute Node Script In Node Shell.

Besides run the javascript file through node command, you can also use node shell to execute the node commands. Open a dos terminal, input node in the command line. Then input console.log(‘Hello World’);, click enter key. You can see the output like below.

C:>node
> console.log('Hello World');
Hello World
undefined
>

5. Question & Answer.

5.1 How to install Node.JS on Windows 7.

  1. My company wants me to install Node.JS on Windows 7 enterprise server. I download the last version of Node.JS and find it can not be installed on Windows 7. Can anybody tell me how to install Node.JS on Windows 7? Thanks.
  2. The latest Node.JS version does not support Windows 7 at all, so you need to ask your company to upgrade the Windows version to Windows 10 or another supported version. Or you can download the older Node.JS version which can be executed on Windows 7, but this is not recommended, because this may lead to security risks.
  3. If you really really want to install the latest Node.JS version on Windows 7, you can follow the below steps.
  4. Download the latest Node.JS binary zip file ( 32-bit or 64-bit ) from the page https://nodejs.org/en/download/ Windows Binary (.zip) section.
  5. Unzip the downloaded zip file to a local folder.
  6. Copy all the unzipped file content to the existing Node.JS installation directory on your Windows to replace the old Node.JS content file.
  7. Create a system environment variable with the name NODE_SKIP_PLATFORM_CHECK, and set the variable value to 1. You can read the article How To Set Windows Environment Variables.
  8. Now open another dos window, and you will find you can use the latest Node.JS version on Windows 7.

Windows 10

http://nodejs.org

Ну что, время завязывать со всякой нудной теорией и переходить к практике. Сейчас мы посмотрим как установить Node.JS, как на нем выполнять скрипты и немножко залезем в документацию. Для этого я первым делом зайду на сайт http://nodejs.org. Здесь есть такая большая кнопка, которая, как правило, позволяет скачать пакет наиболее подходящий для вашей ОС. Вначале посмотрим, что с Mac OS. С Mac OS все просто, мы жмем на кнопку, скачиваем «node-v4.4.7.pkg», запускаем его, все подтверждаем, все очень очевидно, мы не будем это рассматривать, ошибиться тут не возможно.

Следующее это Linux. С Linux все чуть сложнее, потому что в Linux обычно есть различные пакеты, но в пакетах не самая новая версия, а при работе с Node.JS лучше использовать последние версии, если нет каких-то особых причин так не делать. Так что если вы ставите из пакета, то убедитесь, что версия именно последняя. Если у вас пакет устарел, то Node.JS замечательно компилируется из исходников. Для этого можно загуглить «nodejs linux» в первых пяти ссылках обязательно будет инструкция по установке. Можете загуглить установку под какую то определенную систему например «node.js debian» и вы тоже находите инструкцию на первой же странице. Если вы пользуетесь Linux, то этот процесс не составит для вас особого труда.

Ну и наконец Windows. нажимаем на кнопку и скачиваем «node-v4.4.7-x64.msi» —

Screenshot_3_1

после того как он скачался, запускаю и соглашаюсь со всем, что предложит операционная система, все по умолчанию. Отлично Node.JS установился. Установился он в C:Program Filesnodejs и тут есть как файл node.exe так и npm.cmd. NPM это пакетный менеджер мы рассмотрим его немножко позже.

Screenshott_3_2

Node.JS когда ставится прописывает себя в переменную PATH. Чтобы в этом удостовериться можете проделать следующее — в Windows 10 нажимаете правой кнопкой мыши на значок  «windows», который некогда был «пуск». В появившемся окне выбираем «система»

Screenshot_3_3далее жмем на «Дополнительные параметры системы», потом «переменные среды.

Screenshot_3_4Screenshot_3_5

Перед нами появилось окно «переменные среды» в котором нас интересует записи в среду PATH. Причем не важно для всех пользователей или для вашего пользователя (в нижнем окне или в верхнем) главное, что присутствуют записи «C:UsersASUSAppDataRoamingnpm»  и «C:Program Filesnodejs». Теперь проверим работает ли Node.JS в принципе. Для этого в любой папке или на «Рабочем столе» при зажатой клавише «Shift» нажимаем правую кнопку мыши и выбираем «Открыть окно команд» такой трюк позволяет нам открыть консоль с прописанным путем в ту папку в которой мы нажали правую кнопку мыши. Другой способ открыть консоль через меню «пуск». Нажимаем правой кнопкой мыши меню «пуск», выбираем «Командная строка».

Screenshot_3_8

Screenshot_3_9

Итак мы запустили консоль. Вводим команду «node» и у нас появляется приглашение ввести javascript выражение. Это так называемый режим «repl» когда можно вводить javascript выражения и они выполняются.

Screenshot_3_10

Дважды нажав сочетание клавиш «Ctrl + c» мы выходим из этого режима. Вообще этот режим используется достаточно редко, здесь мы его используем просто, чтоб проверить, что установка прошла успешно. Конечно же такой запуск должен работать не только в «Windows», а и из любой операционной системы.

Как правила под Node.JS запускают файлы. Например создадим файл «1.js» и запишем в нем команду:

console.log(«Hello, world!»);

она сделает то же самое, что делает в браузере. В консоли  вводим команду «node 1.js» и жмем «Enter»:

Screenshot_3_11

Обратите внимание в  консоли прописан путь в ту папку, в которой у нас находится наш файл 1.js (в моем случае это рабочий стол).

Если у вас это работает, поздравляю, вы запустили свой первый скрипт под Node.JS!

I’m using Windows as a simple user (I don’t have any admin rights) and want to install NodeJS LTS.

On the download site I have the choice to download only the binary node.exe (which don’t includes npm) or the node.msi installer which requires the admin rights to execute.

How can I manually install node.exe and also be able to use npm?

asked May 4, 2016 at 13:22

Anthony O.'s user avatar

Anthony O.Anthony O.

20.7k15 gold badges102 silver badges159 bronze badges

UPDATE 10/2018

On Node’s download page referenced in step 1. there is now a .zip archive download which contains both the nodejs executable and npm. Unpacking that to a suitable path and adding this path to your PATH environment variable (step 2.) will give you both node and npm (so you can skip steps 3. — 6.).

Let say you want to install it into %userprofile%Applicationsnodejs-lts, let’s name it <NODE_PATH>.

  1. Download the LTS node.exe binary for Windows and copy it to <NODE_PATH>.

  2. Add <NODE_PATH> to your PATH environment variable (set PATH=<NODE_PATH>;%PATH% or using Windows user interface)

  3. Download the stable at https://registry.npmjs.org/npm/-/npm-{VERSION}.tgz npm package (following the documentation)

  4. Unzip the npm-{VERSION}.tgz anywhere (using 7zip for example)

  5. Launch a cmd and cd into the place where you have unzipped npm

  6. Execute: node cli.js install -gf or node bin/npm-cli.js install npm -gf on certain versions (thanks to this comment)

The last command is specified in the Makefile for target install, target which the README.md invites to execute when manually installing.

Ariel_HIAI's user avatar

answered May 4, 2016 at 13:22

Anthony O.'s user avatar

Anthony O.Anthony O.

20.7k15 gold badges102 silver badges159 bronze badges

18

The nodejs version of 6.11 LTS and later seems to be easier to install, because npm is already included.

  1. Download the node.js LTS binary for Windows and extract it to your
    desired location
  2. Add the path of the nodejs folder to the PATH environment variable:
    (Shortcut winkey+R and enter: rundll32 sysdm.cpl,EditEnvironmentVariables)
  3. Open a new command window (winkey+R and type cmd)
  4. Type node -v and npm -v to verify the installation

answered Jul 6, 2017 at 14:04

joerno's user avatar

2

Just download the windows binary (NOT the msi installer) from here, unzip the file, then add the location of the node.exe file to system path. This means that after unzipping the downloaded binary, you get a folder, then you have to open that folder itself. That is the path you should add to system path.

To add to system path, do this, thanks to Abdel Raoof

Open Run with dialog (Win + R). Copy and paste this line in your command line

rundll32 sysdm.cpl,EditEnvironmentVariables.

In User variables for user_name (the top window) path of your environment variables dialog add the path to your unzipped node download.
To check for successful installation

node -v

npm -v

answered Oct 18, 2017 at 11:50

chidimo's user avatar

chidimochidimo

2,4662 gold badges31 silver badges44 bronze badges

4

  1. Download the node.js zip file from official page. https://nodejs.org/en/download/
  2. Unzip the file.
  3. Goto Edit Environment Variables For Your Account.
  4. Add new path /node-v10.14.2-win-x64node-v10.14.2-win-x64
  5. That’s it… now you have installed both node.js and npm.
  6. Use node -v and npm -v to check installation.

answered Dec 24, 2018 at 6:02

Bhargav's user avatar

BhargavBhargav

3554 silver badges10 bronze badges

Add following paths to the PATH environment variable, if you have downloaded the Node.js Windows Binary (.zip)

  1. <your os root>node-v10.16.1-win-x64
  2. <your os root>node-v10.16.1-win-x64node_modulesnpmbin

Then test following commands from the command prompt:

node -v

npm -v

lawrence-witt's user avatar

answered Aug 2, 2019 at 13:31

Rahamath's user avatar

RahamathRahamath

4816 silver badges4 bronze badges

The answer provided is too old now. Portable download for Node (including NPM) is available as a zip download and it word just out of the box. you just need to add the folder to the path.

answered Oct 11, 2017 at 9:02

RPS's user avatar

RPSRPS

611 silver badge2 bronze badges

For node portable installation in windows batch file with below command can also be created in node root directory(where node.exe file resides) which updates PATH environment variable on execution and also directly through command prompt from node root directory

PATH %~dp0;%PATH%;

~dp0 : fetches current directory path in windows

Hopes that Helps

answered Feb 26, 2020 at 11:39

Imran's user avatar

ImranImran

2,8661 gold badge18 silver badges20 bronze badges

As others have pointed out, npm is now included with the binary (.zip) node download. So installing node and npm without admin rights is straightforward, though you need to manually add the node directory to the PATH environment variable.

However, as of v8.11.4, the binary was including npm v5.6.1. Running npm install npm@latest -g complained about not being able to delete npm.cmd and npx.cmd. Moving those files out of the node directory fixes that, but then you can’t simply run npm on the command line, because npm.cmd is no longer on the node path.

Trying @Anthony O’s approach of downloading the latest npm .zip and installing from there didn’t work either, as it was complaining about rimraf not being installed. It seemed like maybe the npm install script was assuming rimraf was installed globally.

What finally worked was changing to the node directory and specifying the full path to npm-cli.js from there:

node node_modules/npm/bin/npm-cli.js install -g npm@latest

I see that the node v8.12.0 package that was just released now includes npm v6.4.1, so the above shouldn’t be necessary for now.

answered Sep 12, 2018 at 16:49

jdunning's user avatar

jdunningjdunning

1,1161 gold badge11 silver badges26 bronze badges

Download the node js zip file, extract it to a folder. Then create a windows batch file to set path to node js folder(as you may not be able to set path the usual way witout admin rights). Then run your node/npm/npx commands from the same command window. You even can open Visual Studio Code from there. If you need step by step checkout this video : https://youtu.be/BLnbtsDIW_E

answered Aug 27, 2020 at 16:48

Don Srinath's user avatar

Don SrinathDon Srinath

1,5451 gold badge21 silver badges32 bronze badges

Accepted answer from @Anothony O. didn’t work for me. I got it working following these instructions and by adding the following to nodenode_modulesnpmnpmrc

strict-ssl=false

desertnaut's user avatar

desertnaut

56k21 gold badges134 silver badges163 bronze badges

answered Aug 30, 2016 at 1:10

Nebu's user avatar

NebuNebu

1,3441 gold badge14 silver badges19 bronze badges

4

Try GitHub n-install:

curl -L https://git.io/n-install | bash -s -- -y

desertnaut's user avatar

desertnaut

56k21 gold badges134 silver badges163 bronze badges

answered Aug 29, 2017 at 22:00

wayofthefuture's user avatar

wayofthefuturewayofthefuture

7,8697 gold badges33 silver badges52 bronze badges

1

I’m using Windows as a simple user (I don’t have any admin rights) and want to install NodeJS LTS.

On the download site I have the choice to download only the binary node.exe (which don’t includes npm) or the node.msi installer which requires the admin rights to execute.

How can I manually install node.exe and also be able to use npm?

asked May 4, 2016 at 13:22

Anthony O.'s user avatar

Anthony O.Anthony O.

20.7k15 gold badges102 silver badges159 bronze badges

UPDATE 10/2018

On Node’s download page referenced in step 1. there is now a .zip archive download which contains both the nodejs executable and npm. Unpacking that to a suitable path and adding this path to your PATH environment variable (step 2.) will give you both node and npm (so you can skip steps 3. — 6.).

Let say you want to install it into %userprofile%Applicationsnodejs-lts, let’s name it <NODE_PATH>.

  1. Download the LTS node.exe binary for Windows and copy it to <NODE_PATH>.

  2. Add <NODE_PATH> to your PATH environment variable (set PATH=<NODE_PATH>;%PATH% or using Windows user interface)

  3. Download the stable at https://registry.npmjs.org/npm/-/npm-{VERSION}.tgz npm package (following the documentation)

  4. Unzip the npm-{VERSION}.tgz anywhere (using 7zip for example)

  5. Launch a cmd and cd into the place where you have unzipped npm

  6. Execute: node cli.js install -gf or node bin/npm-cli.js install npm -gf on certain versions (thanks to this comment)

The last command is specified in the Makefile for target install, target which the README.md invites to execute when manually installing.

Ariel_HIAI's user avatar

answered May 4, 2016 at 13:22

Anthony O.'s user avatar

Anthony O.Anthony O.

20.7k15 gold badges102 silver badges159 bronze badges

18

The nodejs version of 6.11 LTS and later seems to be easier to install, because npm is already included.

  1. Download the node.js LTS binary for Windows and extract it to your
    desired location
  2. Add the path of the nodejs folder to the PATH environment variable:
    (Shortcut winkey+R and enter: rundll32 sysdm.cpl,EditEnvironmentVariables)
  3. Open a new command window (winkey+R and type cmd)
  4. Type node -v and npm -v to verify the installation

answered Jul 6, 2017 at 14:04

joerno's user avatar

2

Just download the windows binary (NOT the msi installer) from here, unzip the file, then add the location of the node.exe file to system path. This means that after unzipping the downloaded binary, you get a folder, then you have to open that folder itself. That is the path you should add to system path.

To add to system path, do this, thanks to Abdel Raoof

Open Run with dialog (Win + R). Copy and paste this line in your command line

rundll32 sysdm.cpl,EditEnvironmentVariables.

In User variables for user_name (the top window) path of your environment variables dialog add the path to your unzipped node download.
To check for successful installation

node -v

npm -v

answered Oct 18, 2017 at 11:50

chidimo's user avatar

chidimochidimo

2,4662 gold badges31 silver badges44 bronze badges

4

  1. Download the node.js zip file from official page. https://nodejs.org/en/download/
  2. Unzip the file.
  3. Goto Edit Environment Variables For Your Account.
  4. Add new path /node-v10.14.2-win-x64node-v10.14.2-win-x64
  5. That’s it… now you have installed both node.js and npm.
  6. Use node -v and npm -v to check installation.

answered Dec 24, 2018 at 6:02

Bhargav's user avatar

BhargavBhargav

3554 silver badges10 bronze badges

Add following paths to the PATH environment variable, if you have downloaded the Node.js Windows Binary (.zip)

  1. <your os root>node-v10.16.1-win-x64
  2. <your os root>node-v10.16.1-win-x64node_modulesnpmbin

Then test following commands from the command prompt:

node -v

npm -v

lawrence-witt's user avatar

answered Aug 2, 2019 at 13:31

Rahamath's user avatar

RahamathRahamath

4816 silver badges4 bronze badges

The answer provided is too old now. Portable download for Node (including NPM) is available as a zip download and it word just out of the box. you just need to add the folder to the path.

answered Oct 11, 2017 at 9:02

RPS's user avatar

RPSRPS

611 silver badge2 bronze badges

For node portable installation in windows batch file with below command can also be created in node root directory(where node.exe file resides) which updates PATH environment variable on execution and also directly through command prompt from node root directory

PATH %~dp0;%PATH%;

~dp0 : fetches current directory path in windows

Hopes that Helps

answered Feb 26, 2020 at 11:39

Imran's user avatar

ImranImran

2,8661 gold badge18 silver badges20 bronze badges

As others have pointed out, npm is now included with the binary (.zip) node download. So installing node and npm without admin rights is straightforward, though you need to manually add the node directory to the PATH environment variable.

However, as of v8.11.4, the binary was including npm v5.6.1. Running npm install npm@latest -g complained about not being able to delete npm.cmd and npx.cmd. Moving those files out of the node directory fixes that, but then you can’t simply run npm on the command line, because npm.cmd is no longer on the node path.

Trying @Anthony O’s approach of downloading the latest npm .zip and installing from there didn’t work either, as it was complaining about rimraf not being installed. It seemed like maybe the npm install script was assuming rimraf was installed globally.

What finally worked was changing to the node directory and specifying the full path to npm-cli.js from there:

node node_modules/npm/bin/npm-cli.js install -g npm@latest

I see that the node v8.12.0 package that was just released now includes npm v6.4.1, so the above shouldn’t be necessary for now.

answered Sep 12, 2018 at 16:49

jdunning's user avatar

jdunningjdunning

1,1161 gold badge11 silver badges26 bronze badges

Download the node js zip file, extract it to a folder. Then create a windows batch file to set path to node js folder(as you may not be able to set path the usual way witout admin rights). Then run your node/npm/npx commands from the same command window. You even can open Visual Studio Code from there. If you need step by step checkout this video : https://youtu.be/BLnbtsDIW_E

answered Aug 27, 2020 at 16:48

Don Srinath's user avatar

Don SrinathDon Srinath

1,5451 gold badge21 silver badges32 bronze badges

Accepted answer from @Anothony O. didn’t work for me. I got it working following these instructions and by adding the following to nodenode_modulesnpmnpmrc

strict-ssl=false

desertnaut's user avatar

desertnaut

56k21 gold badges134 silver badges163 bronze badges

answered Aug 30, 2016 at 1:10

Nebu's user avatar

NebuNebu

1,3441 gold badge14 silver badges19 bronze badges

4

Try GitHub n-install:

curl -L https://git.io/n-install | bash -s -- -y

desertnaut's user avatar

desertnaut

56k21 gold badges134 silver badges163 bronze badges

answered Aug 29, 2017 at 22:00

wayofthefuture's user avatar

wayofthefuturewayofthefuture

7,8697 gold badges33 silver badges52 bronze badges

1

How to Install Node.js and npm on Windows

Installing Node.js and npm on Windows is very straightforward.

First, download the Windows installer from the Node.js website. You will have the choice between the LTS (Long Term Support) or Current version.

  • The Current version receives the latest features and updates more rapidly
  • The LTS version foregos feature changes to improve stability, but receives patches such as bug fixes and security updates

Once you have selected a version meets your needs, run the installer. Follow the prompts to select an install path and ensure the npm package manager feature is included along with the Node.js runtime. This should be the default configuration.

Restart your computer after the installation is complete.

If you installed under the default configuration, Node.js should now be added to your PATH. Run command prompt or powershell and input the following to test it out:

> node -v

The console should respond with a version string. Repeat the process for npm:

> npm -v

If both commands work, your installation was a success, and you can start using Node.js!

More info on Node.js

According to its GitHub repository, Node.js is:

Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser. For more information on using Node.js, see the Node.js Website.

A breakdown of Node.js facts:

  • Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
    Every browser has a JavaSript engine built in it to process JavaScript files contained in websites. Google Chrome uses the V8 engine, which is built using C++. Node.js also uses this super-fast engine to interpret JavaScript files.
  • Node.js uses an event-driven model.
    This means that Node.js waits for certain events to take place. It then acts on those events. Events can be anything from a click to a HTTP request. We can also declare our own custom events and make Node.js listen for those events.
  • Node.js uses a non-blocking I/O model.
    We know that I/O tasks take much longer than processing tasks. Node.js uses callback functions to handle such requests.

Let us assume that a particular I/O task takes 5 seconds to execute, and that we want to perform this I/O twice in our code.

Python

import time

def my_io_task():
  time.sleep(5)
  print("done")

my_io_task()
my_io_task()

Node.js

function my_io_task() {
    setTimeout(function() {
      console.log('done');
    }, 5000);
}

my_io_task();
my_io_task();

Both look similar, but the time taken to execute are different. The Python code takes 10 seconds to execute while the Node.js code takes only 5 seconds.

Node.js takes less time because of its non-blocking I/O model. The first call to my_io_task() starts the timer and leaves it there. It does not wait for the response from the function. Instead, it moves on to call the second my_io_task(), starts the timer and leaves it there.

When the timer completes it’s execution taking 5 seconds, it calls the function and prints done on the console. Since both the timers are started together, they complete together and therefore take same amount of time.

Socket.io

Socket.io is a Node.js library made to help make real-time communication between computers possible. To ensure this Socket.io uses WebSockets to establish a connection between the client’s browser and the server. This library uses Engine.IO for building the connection.

Demos

To get a taste of what is possible, Socket.io provides two demos to show it’s possible use-cases. You can find the demos at https://socket.io/demos/chat/ and find the link to the whiteboard demo on the left.

Get Started

Since Socket.io is a Node.js library you have to make sure that Node.js is installed. If it’s not set up yet get the latest version at Nodejs.org

macOS

Node.js can also be installed via Homebrew a package manager for macOS.

Just type brew install node to install Node.js.

A get started guide can also be found on Socket.io’s page. It shows how to easily build a real-time chat in just a couple of lines.

More information

More information about Socket.io and it’s documentation can be found at:

  • Socket.io
  • Socket.io Documentation

More information on Node.js

  • Official Node.js site
  • Node Version Manager
  • n: Interactive Node.js Version Manager
  • Node.js docs

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Как добавить блютуз в центр уведомлений windows 10
  • Как добавить miracast в windows 10
  • Как добавить mingw в path windows 10
  • Как добавить блютуз в скрытые значки windows 10
  • Как добавить microsoft store в windows 10 enterprise ltsc