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

от admin

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

Ну что, время завязывать со всякой нудной теорией и переходить к практике. Сейчас мы посмотрим как установить 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» —

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

Screenshott_3_2

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

Screenshot_3_3

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

Screenshot_3_4Screenshot_3_5

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

Screenshot_3_8

Screenshot_3_9

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

Screenshot_3_10

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

Install Node.js on Windows

The Node can be installed in multiple ways on a computer. The approach used by you depends on the existing development environment in the system. There are different package installer for different environments. You can install Node by grabbing a copy of the source code and compiling the application. Another way of installing Node is by cloning the GIT repository in all the three environments and then installing it on the system.

Installing Node On Windows (WINDOWS 10):

You have to follow the following steps to install the Node.js on your Windows :

Step-1: Downloading the Node.js ‘.msi’ installer.

The first step to install Node.js on windows is to download the installer. Visit the official Node.js website i.e) https://nodejs.org/en/download/ and download the .msi file according to your system environment (32-bit & 64-bit). An MSI installer will be downloaded on your system.

Step-2: Running the Node.js installer.

Now you need to install the node.js installer on your PC. You need to follow the following steps for the Node.js to be installed:-

  • Double click on the .msi installer.
  • The Node.js Setup wizard will open.
  • Welcome To Node.js Setup Wizard.
  • Select “Next”
  • After clicking “Next”, End-User License Agreement (EULA) will open.
  • Check “I accept the terms in the License Agreement”
  • Select “Next”
  • Destination Folder
  • Set the Destination Folder where you want to install Node.js & Select “Next”
  • Custom Setup
  • Select “Next”
  • Ready to Install Node.js.
  • Select “Install”
  • NOTE :
  • A prompt saying — “This step requires administrative privileges” will appear.
  • Authenticate the prompt as an “Administrator”
  • Installing Node.js.
  • Do not close or cancel the installer until the install is complete
  • Complete the Node.js Setup Wizard.
  • Click “Finish”

Step 3: Verify that Node.js was properly installed or not.

To check that node.js was completely installed on your system or not, you can run the following command in your command prompt or Windows Powershell and test it:-

If node.js was completely installed on your system, the command prompt will print the version of the node.js installed.

Step 4: Updating the Local npm version.

The final step in node.js installed is the updation of your local npm version(if required) — the package manager that comes bundled with Node.js.

Читать:
Как настроить время на духовом шкафу weissgauff

You can run the following command, to quickly update the npm

npm install npm –global // Updates the ‘CLI’ client

NOTE :

  • You do not need to do anything to the system variables as the windows installer takes care of the system variables itself while installing through the .msi installer
  • If you use any other format for installing node.js on your PC, you should put the system variable path for node.js as follows:
  • PATH : C:\Users\[username]\AppData\Roaming\npm
    C:\Program Files\nodejs (Path to the nodejs folder)

Hope This article was helpful !

If you have any queries or questions please share it in the comments section.

Installing Node.js (and npm) on Windows 10

I had some issues trying to install Node on Windows 10 and found the solution.

The error was as follows:

C:\Users\Stephan>npm
Error: ENOENT, stat ‘C:\Users\Stephan\AppData\Roaming\npm’

The solution is below.

Stephan Bijzitter's user avatar

10 Answers 10

Edit: It seems like new installers do not have this problem anymore, see this answer by Parag Meshram as my answer is likely obsolete now.

Original answer:

Follow these steps, closely:

    download the 64 bits version, 32 is for hipsters
  • Install it anywhere you want, by default: C:\Program Files\nodejs
  • Control Panel -> System -> Advanced system settings -> Environment Variables
  • Select PATH and choose to edit it.

If the PATH variable is empty , change it to this: C:\Users\\AppData\Roaming\npm;C:\Program Files\nodejs

If the PATH variable already contains C:\Users\\AppData\Roaming\npm , append the following right after: ;C:\Program Files\nodejs

If the PATH variable contains information, but nothing regarding npm, append this to the end of the PATH: ;C:\Users\\AppData\Roaming\npm;C:\Program Files\nodejs

Now that the PATH variable is set correctly, you will still encounter errors. Manually go into the AppData directory and you will find that there is no npm directory inside Roaming. Manually create this directory.

Re-start the command prompt and npm will now work.

Stephan Bijzitter's user avatar

and hit the button that says «Download For . «

This’ll download the .msi (or .pkg for mac) which will do all the installation and paths for you, unlike the selected answer.

Shai UI's user avatar

In addition to the answer from @StephanBijzitter I would use the following PATH variables instead:

So your new PATH would look like:

This has the advantage of neiter being user dependent nor 32/64bit dependent.

New installers (.msi downloaded from https://nodejs.org) have «Add to PATH» option. By default it is selected. Make sure that you leave it checked.

Add to PATH

activedecay's user avatar

Parag Meshram's user avatar

Everything should be installed in %appdata% (C:\Users\\AppData\Roaming), not ‘program files’.

The default MSI installer puts Node and the NPM that comes with it in ‘program files’ and adds this to the system path, but it sets the user path for NPM to %appdata% (c:\users[username]\appdata\roaming) since the user doesn’t have sufficient priveleges to write to ‘program files’.

This creates a mess as all modules go into %appdata%, and when you upgrade NPM itself — which NPM themselves recommend you do right away — you end up with two copies: the original still in ‘program files’ since NPM can’t erase that, and the new one inn %appdata%.

Even worse, if you mistakenly perform NPM operations as admin (much easier on Windows then on *nix) then it will operate on the ‘program files’ copy of NPM node_modules. Potentially a real mess.

So, when you run the installer simply point it to %appdata% and avoid all this.

And note that this isn’t anything wierd — it’s what would happen if you ran the installer with just user priveleges.

Installing Node.js® and NPM on Windows

Node.js® is a JavaScript-based environment which you can use to create web-servers and networked applications. You can also use it to perform helpful tasks on your computer such as concatenating and minifying JavaScript files and compiling Sass files into CSS.

NPM is a “package manager” that makes installing Node “packages” fast and easy. A package is just a code library that extends Node by adding useful features. For example, the “request” package simplifies the process of making HTTP requests so you can easily get web resources from other sites.

NPM is installed when you install Node.js®

Prerequisites

  • You should have some familiarity with an application that lets you issue command line instructions. For example, the Windows Command Prompt, PowerShell, Cygwin, or the Git shell (which you get when you install Github for Windows).

Installation Overview

Installing Node.js® and NPM is pretty straightforward using the installer package available from the Node.js web site.

Installation Steps

  1. Download the Windows installer from Nodejs.org.
  2. Run the installer (the .msi file you downloaded in the previous step.)
  3. Follow the prompts in the installer (Accept the license agreement, click the NEXT button a bunch of times and accept the default installation settings).
  4. Restart your computer. You won’t be able to run Node.js until you restart your computer.

Test it!

Make sure you have Node and NPM installed by running simple commands to see what version of each is installed:

Похожие статьи