Установка Node.js в Ubuntu 20.04
Node Js — это платформа на основе JavaScript, которая уже завоевала большую популярность и становится еще более легкой и эффективной для разработчиков. Она позволяет программистам использовать JavaScript как для веб-приложений и пользовательских интерфейсов, так и для обычных программ, благодаря движку V8 от Google.
Для платформы уже создано более чем миллион пакетов, которыми можно управлять с помощью менеджера пакетов Node или NPM. Это отличная система для расширяемости приложения с помощью решений с открытым исходным кодом. В этой статье мы рассмотрим четыре способа установить Node.js в Ubuntu 20.04. Мы рассмотрим их все ниже, но рекомендуется использовать первый:
- Использовать скрипт NVM, для управления несколькими версиями Node.js;
- Установить программу из официальных репозиториев вашего дистрибутива;
- Установить пакеты из PPA;
- Установка Node.js из бинарных пакетов, распространяемых на официальном сайте;
Первый способ рекомендованный, но второй более простой, третий и четвертый позволяют получить более новые версии программ. Если у вас уже была установлена более старая версия Node js, ее нужно удалить, чтобы не возникало конфликтов, также вы можете просто обновить программу, для этого смотрите статью как обновить Node.js на Windows, Linux и Mac.
Удалить старую версию Node.js
В Ubuntu пакет Node Js называется по-старому — Node, эта программа вам не нужна и вы можете ее удалить. Если программа останется, некоторые операции могут выполняться с помощью нее и это будет вызывать конфликты.
Сначала давайте проверим установлена ли у вас эта программа:
dpkg —get-selections | grep node
Теперь вы можете ее удалить с помощью следующих команд:
sudo apt purge nodejs

Теперь можно переходить к рассмотрению того как установить Node.js в Ubuntu 20.04.
Установка Node.js в Node Version Manager
Чтобы установить Node.js Ubuntu 20.04 с помощью NVM нам понадобится компилятор C++ в системе, а также другие инструменты для сборки. По умолчанию система не поставляется с этими программами, поэтому их необходимо установить. Для этого выполните команду:
sudo apt install build-essential checkinstall
Также нам понадобится libssl:
sudo apt install libssl-dev
Скачать и установить менеджер версий NVM можно с помощью следующей команды:
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash

После завершения установки вам понадобится перезапустить терминал. Или можно выполнить:
Затем смотрим список доступных версий Node js:

Дальше можно устанавливать Node js в Ubuntu, при установке обязательно указывать версию, на данный момент самая последняя 11.0, но установим десятую:
nvm install 14.0

Список установленных версий вы можете посмотреть выполнив:

Дальше необходимо указать менеджеру какую версию нужно использовать:
Как только появятся более новые версии node js, вы сможете их установить и активировать в системе. Посмотреть версию вы можете выполнив команду:

Чтобы удалить эту версию node js, ее нужно деактивировать:
nvm deactivate 14.0
Затем можно удалить:
nvm uninstall 14.0
Установка Node.js из репозиториев Ubuntu
Это самый простой способ установки этой платформы. Сначала выполните команду:
sudo apt install nodejs

Затем установите менеджер пакетов npm:
sudo apt install npm
Теперь вы можете проверить работоспособность только что установленных программ:

Как видите, при использовании официальных репозиториев вы получаете более старую версию.
Установка Node js из PPA
Установка Node js Ubuntu из PPA, это альтернативный вариант, позволяющий получить более новую версию, достаточно простым способом. Сначала добавьте репозитории Node js в список репозиториев Ubuntu с помощью такой одной из следующих команд. Для установки самой последней версии выполните:
curl -sL https://deb.nodesource.com/setup_15.x | sudo bash —

А для стабильной:
curl -sL https://deb.nodesource.com/setup_14.x | sudo bash —
Затем просто установите программу с помощью пакетного менеджера:
sudo apt install nodejs

Проверяем, что получилось:

Установка Node js из бинарников
Установка Node.js Ubuntu 20.04 через бинарные файлы не рекомендуется, потому что вы не сможете автоматически обновить программу до новой версии, вам придется повторять процедуру заново. Вы можете скачать установочные файлы Node js из официального сайта проекта. Здесь доступны как 32 битная, так и 64 битная версия. Вам нужно скачать файл именно для своей системы.
Чтобы узнать архитектуру выполните:

Откройте официальный сайт Node.js и найдите нужную версию, затем скачайте архив для своей архитектуры:

Вы можете скачать Node js и с помощью терминала, например, эта команда для 64 бит версии:
Теперь распаковываем бинарные файлы программы:
sudo tar -C /usr/local —strip-components 1 -xf ./node-v15.0.0-linux-x64.tar.gz
Смотрим версию, чтобы убедится, что все работает:

Выводы
В этой статье была рассмотрена установка Node.js Ubuntu 20.04 популярной платформы для программирования на JavaScript. Мы рассмотрели различные способы установки, если у вас остались вопросы, спрашивайте в комментариях!
Как я могу обновить свой nodeJS до последней версии?
Для установки nodejs лучше использовать nvm. Это означает «Диспетчер версий узлов». Вы можете очень легко установить несколько версий nodejs, переключаться между ними и устанавливать значения по умолчанию.
Используйте модуль n от npm для обновления узла
sudo npm cache clean -f sudo npm install -g n sudo n stable
Для обновления до последней версии (а не текущей стабильной) вы можете использовать
sudo n latest
Отменить:
sudo apt-get install --reinstall nodejs-legacy # fix /usr/bin/node sudo n rm 6.0.0 # replace number with version of Node that was installed sudo npm uninstall -g n
это должен быть правильный ответ. n является вспомогательным пакетом узла, который устанавливает или обновляет данную версию node.js
Я бы настоятельно рекомендовал не делать этого на производственном экземпляре. Это может серьезно испортить ваши глобальные пакеты npm и вашу возможность устанавливать новые.
но все же nodejs
Не работает — после выполнения шагов node -v все равно дал мне 6 версию, а не 10.
Полные инструкции по установке были загружены здесь Nodesource. Это скопировано ниже для вашей справки. Инструкции одинаковы для обновления до последней версии.
Node.js v12.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 6.x в старых дистрибутивах.
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_12.x | bash - apt-get install -y nodejs
Node.js v11.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 6.x в старых дистрибутивах.
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_11.x | bash - apt-get install -y nodejs
Node.js v10.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 6.x в старых дистрибутивах.
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_10.x | bash - apt-get install -y nodejs
Node.js v9.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 6.x в старых дистрибутивах.
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_9.x | bash - apt-get install -y nodejs
Node.js v8.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 6.x в старых дистрибутивах.
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_8.x | bash - apt-get install -y nodejs
Node.js v7.x :
ПРИМЕЧАНИЕ: пакеты Debian Wheezy и Ubuntu Precise НЕ доступны для этого выпуска. Пожалуйста, укажите запуск Node.js> = 4.x на старых дистрибутивах
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_7.x | bash - apt-get install -y nodejs
Node.js v6.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 4.x в старых дистрибутивах .
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_6.x | bash - apt-get install -y nodejs
Node.js v5.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 4.x в старых дистрибутивах .
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_5.x | bash - apt-get install -y nodejs
Node.js v4.x :
ПРИМЕЧАНИЕ. Если вы используете Ubuntu Precise или Debian Wheezy, вы можете прочитать о запуске Node.js> = 4.x в старых дистрибутивах .
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_4.x | bash - apt-get install -y nodejs
Node.js v0.12 :
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_0.12 | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_0.12 | bash - apt-get install -y nodejs
Node.js v0.10 :
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_0.10 | sudo -E bash - sudo apt-get install -y nodejs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_0.10 | bash - apt-get install -y nodejs
io.js v3.x :
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_iojs_3.x | sudo -E bash - sudo apt-get install -y iojs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_iojs_3.x | bash - apt-get install -y iojs
io.js v2.x :
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_iojs_2.x | sudo -E bash - sudo apt-get install -y iojs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_iojs_2.x | bash - apt-get install -y iojs
io.js v1.x :
Примечание: эта ветка io.js активно не поддерживается и не рекомендуется для производственного использования.
# Using Ubuntu curl -sL https://deb.nodesource.com/setup_iojs_1.x | sudo -E bash - sudo apt-get install -y iojs # Using Debian, as root curl -sL https://deb.nodesource.com/setup_iojs_1.x | bash - apt-get install -y iojs
Я бы посоветовал либо удалить устаревшую информацию, либо переместить ее в конец вопроса, чтобы текущая информация читалась первой.
Это ответ, который работал для меня!
Кажется, что для всех запутавшихся идиотов, подобных мне, запуск установки эффективно заменит то, что у вас было раньше. Поэтому я думаю, что вы можете выполнить обновление или понижение с этим процессом. Я обновил с v8 до v10 и обнаружил это сообщение в журналах установки: Unpacking nodejs (10.15.0-1nodesource1) over (8.12.0-1nodesource1) . запуск node -v после того, как установка успешно отображает v10.15.0 то, что я хочу.
curl
@krubo Я согласен. Пользователь должен изучить скрипт перед его запуском. Тем не менее, это от авторитетного источника ( nodesource.com ) и соединение обеспечивается с помощью HTTPS, так что есть достаточное количество доверия , которое Вы можете разместить в этих сценариях. Но да, в общем, проверяйте сценарии, прежде чем sudo bash
Этот PPA устарел и больше не поддерживается; Вы должны рассмотреть другие ответы вместо этого.
Вы можете установить последнюю версию из PPA:
sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs
Я думаю, что это был бы лучший ответ, если бы вы (также) предоставили не-ppa способ сделать это, ppas, как известно, известны как устаревшие и не поддерживаемые, по сути, делая ответ бесполезным.
@ bigbadonk420 да, если вы просто погуглили, вероятно, лучше пропустить первую строку и просто обновить и установить — у меня работает с узлом 0.10.34
@Capaj Нету. это не помогло .
Больше не рекомендую использовать этот ppa, кажется, он устарел.
Я использую NVM для обработки своих версий Node. Очень прост в настройке и прост в использовании.
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
Вместо этого, чтобы установить NVM глобально, используйте следующую команду curl вместо приведенной выше (и, вероятно, не используйте вторую команду, но используйте третью)
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | NVM_DIR=/usr/local/nvm bash
Затем используйте nvm install stable (или вставьте номер версии вместо stable ), чтобы получить последнюю / конкретную версию Node. Используйте nvm use stable (или конкретный номер версии), чтобы использовать эту версию Node. Используйте, nvm ls чтобы увидеть, какие версии Node вы установили и nvm uninstall stable (или конкретный номер версии), чтобы удалить конкретную версию Node.
Хотя это может теоретически ответить на вопрос, было бы предпочтительным включить здесь основные части ответа и предоставить ссылку для справки.
Извиняюсь за мою новизну. Обновленный ответ
Не забудьте обновить часть URL до последней версии nvm
Я также рекомендую вместо этого использовать nvm, а также удалить уже установленную версию, чтобы избежать конфликтов в терминале
sudo apt purge nodejs npm
затем установите nvm и используйте его
Видео Объяснение
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
скачать и установить NVM
nvm install node
следует скачать и установить последнюю версию узла.
Чтобы обновить узел позже просто сделайте
nvm install node nvm alias default node
Это должен быть единственный принятый ответ — в случае, если вы хотите иметь в Ubuntu правильную и актуальную настройку Node.
Это также работает лучше всего для меня (у нас на EC2 были довольно древние nodejs, и я попробовал множество предложений, и только этот заставил его работать). Также 100% согласны с комментарием выше!
nvm устанавливает Node.js для каждого пользователя. Использование nvm не даст вам общесистемную node команду. Поэтому я бы посоветовал не удалять глобальную / системную систему, node чтобы можно было запускать сценарии, выполняемые от имени другого пользователя node .
Я попробовал те же самые команды списка на моем Ubuntu 14.04, но он все еще выдавал ошибку.
Команды, которые я выполнил, были:
sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs
и ошибка, которую я получаю:
Invalid version 0.12.2 Line 299: curl not found in /bin/n
Я понял, что утилита curl не установлена на моей ОС.
Я выполнил команду:
apt-get install curl
(используйте в sudo качестве префикса, если вы не su )
а потом повторил шаги подсказки в ответ и все заработало;)
Этот устанавливает последний узел v0.12. * Из nodeource.
sudo apt-get install -y curl curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash - sudo apt-get install -y nodejs
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash - sudo apt-get install -y nodejs
Вы устанавливаете узел с нуля? Вопрос был об обновлении, не устанавливающем
Использование NVM является предпочтительным методом. Сначала установите NVM:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
Затем установите nodejs:
nvm install node
Теперь вы можете легко переключать версии узла.
NVM (менеджер версий узлов) с —lts
NVM был упомянут по адресу: https://askubuntu.com/a/441527/52975, но здесь приведен более полный пример использования, включая нормальную —lts версию.
NVM устанавливает для вас как последний стабильный узел, так и npm
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | sh source ~/.nvm/nvm.sh nvm install --lts nvm use --lts npm --version
Теперь проверьте это с помощью фиктивного пакета:
npm install --global vaca vaca
Так как поиск источников должен быть выполнен для каждой новой оболочки, хаки установочного скрипта добавляют некоторую автоматическую загрузку в конец вашей .barshrc . Это работает, но я предпочитаю удалить автоматически добавленный и добавить свой собственный:
f="$HOME/.nvm/nvm.sh" if [ -r "$f" ]; then . "$f" &>'/dev/null' nvm use --lts &>'/dev/null' fi
- позволяет использовать несколько версий Node и без sudo
- является аналогом Ruby RVM и Python Virtualenv, широко признанным лучшим опытом в сообществах Ruby и Python
- по возможности загружает предварительно скомпилированный двоичный файл, а если нет, то загружает исходный код и компилирует его для вас
Мы можем легко переключать версии узлов с помощью:
nvm install 0.9.0 nvm install 0.9.9 nvm use 0.9.0 node --version #v0.9.0 nvm use 0.9.9 node --version #v0.9.9
Затем вы можете использовать отслеживаемый .nvmrc файл git для указания версии узла, необходимой для данного проекта: https://stackoverflow.com/questions/24869959/how-do-i-specify-a-local-version-of-node-for -a-проект / 54503474 # 54503474
Протестировано в Ubuntu 17.10.
Я советую сначала удалить все установки nodejs, а затем выполнить приведенный ниже скрипт, как только вы отредактируете нужную версию nodejs и ее родительский каталог установки
увидеть все доступные версии nodejs
Скрипт ниже позволит вам установить любую из этих версий nodejs на Linux или OSX.
#!/bin/bash # usage : # # edit two vars in below : NODE_VER and CODE_PARENT_DIR # # . execute this script as yourself unless you choose a root owned value for var CODE_PARENT_DIR # whichever id you execute this as determines the id you will issue npm commands as : npm install -g foo-bar # # NOTE - nodejs comes bundled with npm . so no need to do separate npm install # this scripts runs fine on linux or OSX # . copy all the lines starting here .. top of copy . and ending . end of copy . # and paste into your ~/.bashrc file so proper env vars get set # . top of copy . install_node.sh # export NODE_VER=v7.2.0 # see available versions at https://nodejs.org/dist/ # export NODE_VER=v8.5.0 # edit this line next time you need to update nodejs export NODE_VER=v9.3.0 # edit this line next time you need to update nodejs # . pick parent dir of nodejs install . comment out or remove ONE of below # export CODE_PARENT_DIR=/opt/code # root owned dir . requires you to sudo prior to npm install going forward export CODE_PARENT_DIR=$ # RECOMMENDED execute as yourself including npm install # . following env vars are OK no edits needed . only ever need to edit above vars curr_OS=$( uname ) echo curr_OS $curr_OS if [[ "$" == "Darwin" ]]; then OS_ARCH=darwin-x64 elif [[ "$" == "Linux" ]]; then OS_ARCH=linux-x64 else echo "ERROR - failed to recognize OS $curr_OS" exit 5 fi if [[ -z $ ]]; then echo "ERROR - failed to see env var CODE_PARENT_DIR" exit 5 fi export NODE_CODEDIR=$/nodejs export COMSUFFIX=tar.gz export NODE_NAME=node-$ export NODE_PARENT=$/$-$ export PATH=$/bin:$ export NODE_PATH=$/lib/node_modules # . end of copy . install_node.sh # copy and paste above from . top of copy . to here into your file ~/.bashrc echo echo "NODE_CODEDIR $NODE_CODEDIR<--" echo echo "mkdir -p $" echo mkdir -p $ echo echo "cd $" cd $ echo # this is compiled code NOT source [ -f $-$.$ ] && rm $-$.$ # if file exists remove echo "wget -q --show-progress https://nodejs.org/download/release/$/$-$.$" wget -q --show-progress https://nodejs.org/download/release/$/$-$.$ echo echo "tar -C $ -xf $-$.$" tar -C $ -xf $-$.$ echo [ -f $-$.$ ] && rm $-$.$ # if file exists remove # . done . # which node node --version # . bottom of file install_node.sh
How to Update Node.js to Latest Version
Node.js is an open-source JavaScript runtime environment. Since Node.js has an active community of users, minor updates of the software come out every few weeks.
You may be using Node.js as a layer of the MEAN stack or in a different JS framework. Either way, make sure to update Node.js regularly to ensure system security.
There are several ways to install Node.js and NPM. Likewise, there are several ways to update your Node.js version, depending on the operating system running on your machine.
In this article, you will learn how to update to the latest Node.js version on Linux, Windows, and macOS.

3 Ways to Update Node.js to Latest Version on Linux Systems
There are different ways to update Node.js if you are using a Linux-based system. Although using the Node Version Manager is the easiest and most recommended option, you can also update with the local package manager or by downloading the binary packages.
Option 1: Update Node.js with NVM (Node Version Manager)
The best way to upgrade Node.js is with NVM, a practical tool for managing multiple Node.js versions.
1. Start by updating the package repository with the command:
sudo apt update
2. Install NVM using the curl command:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
Note: If you don't have curl , install the utility by running the command: sudo apt install curl .
Alternatively, you use wget and run the command:
wget -q0- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
3. Close and reopen the terminal for system to recognize the changes or run the command:
source ~/.bashrc
5. Then, verify if you have successfully installed NVM:
nvm --version

6. Before upgrading Node.js, check which version you have running on the system:
nvm ls
7. Now you can check for newly available releases with:
nvm ls-remote

8. To install the latest version, use the nvm command with the specific Node.js version:
nvm install [version.number]
Option 2: Update Node.js with NPM (Node Package Manager)
As an alternative, you can use Node’s official package manager to update Node.js. NPM is a tool for installing and managing package dependencies.
If you have Node on your system, you have NPM, as well. With the npm command, you can check running Node.js versions and install the latest release.
By adding the n module, you can interactively manage Node.js versions.
1. First, clear the npm cache:
npm cache clean -f

2. Install n, Node’s version manager:
npm install -g n

3. With the n module installed, you can use it to:
Install the latest stable version:
sudo n stable

Note: Some Ubuntu distros may respond with the command not found output after running the n command. To fix this issue run sudo -E env "PATH=$PATH" [command] . For example, to install the latest stable version, as in the example above, you would run sudo -E env "PATH=$PATH" n stable .
Install the latest release:
sudo n latest

Install a specific version:
sudo n [version.number]

Option 3: Update Node.js with Binary Packages
Updating Node.js with binary packages is the least recommended option. However, if it is the only way you can upgrade to the latest Node.js version, follow the steps outlined below.
1. Navigate to Node’s official downloads page where you can find all available packages. There you can download the source code or pre-built installer for the LTS versions or the latest release.

2. You can either download the package from your browser or find the version number you need and add it to the wget command:
wget https://nodejs.org/dist/v14.17.0/node-v14.17.0-linux-x64.tar.xz
3. Next, install xz-utils used to extract the binary package:
sudo apt-get install xz-utils
4. Extract and install the package with the command:
sudo tar -C /usr/local --strip-components 1 -xJf node-v14.17.0-linux-x64.tar.xz
Update Node.js to Latest Version on Windows and macOS
Updating Node.js on Windows and macOS follows the same principles.
There are two simple ways to upgrade:
- Download the latest Node.js release from its official download page and install the new Node.js release.
- Install the n module and update Node.js inside the terminal window.
Option 1: Update Node.js on Windows and macOS with Installer
One way to update your Node.js is to go to its official download page and install the newest release. Bz doing so, the system should overwrite the older version with the updated one.
1. Navigate to the Node.js website and click on the latest stable version or the newest current release (with the latest features).
2. After deciding the version, click on the Windows or the macOS Installer, depending on the system you are using. The system downloads the package and stores it in the specified directory.

3. Once the download is complete, run the installer.
4. The Node.js Setup Wizard appears and guides you through the installation.

5. Accept the License Agreement by checking the box and click Next.

6. Choose the destination folder where you want to install Node.js.

7. Node.js allows you to select how you want to install the Node features. Change the way the features are installed by clicking on the icons in the tree.

8. With that, the latest Node.js is ready to install. Click Install to confirm, wait until the installation completes, and click Finish.
9. Check the Node.js version with the command:
node -v
Note: Sometimes, the system fails to overwrite the older Node.js release and you may end up with two versions. If such problems occur, you may want to consider updating with NPM, outlined in the section below.
Option 2: Update Node.js on Windows and macOS with NPM
If you want to upgrade Node.js from the command line, use the n model within the npm command. The n feature allows you to interact with different Node.js versions.
1. Before updating the Node.js release, check which version you are currently using with:
node -v
2. Next, clear npm cache with the command:
npm cache clean -f
3. Install n globally:
npm install -g n
4. Now that you have n installed, you can use the module to install the latest stable release of Node.js:
sudo n stable
Alternatively, you can install the Node.js release with the latest features:
sudo n latest
Or, install a specific version number with:
n [version.number]
The best part of open-source technology is its strong community of users constantly working on upgrading the software.
Node.js is a good example of such software as new versions come out regularly. Users can choose whether they want to work with the LTS (the long-term supported version) or the latest version with the newest features.
This article should have helped you update Node.js on any operating system.
Was this article helpful?
Sofija Simic
Sofija Simic is an experienced Technical Writer. Alongside her educational background in teaching and writing, she has had a lifelong passion for information technology. She is committed to unscrambling confusing IT concepts and streamlining intricate software installations.
Next you should read
March 18, 2019
Node.js is an open-source cross-platform JavaScript (JS) runtime environment. It is used for building fast.
April 9, 2019
The MEAN stack is an open-source JavaScript (JS) framework used for developing robust web applications. It is.
June 29, 2019
Node Package Manager (npm) is Node's official package manager, used for installing and managing packages.
October 28, 2019
Node.js is a software application that runs JavaScript code. It's typically used for running scripts on the.
How can I update Node.js and NPM to their latest versions?
I just installed Node.js and NPM (Node Package Manager). I installed NPM for access to additional Node.js modules. After I installed Node.js and NPM, I noticed that neither were the latest versions available. How do I upgrade Node.js, NPM, and my Node.js Modules to their latest versions? Do I need to uninstall Node.js and NPM, and reinstall the latest versions? Here is the link to what I have tried so far. This link is a section from npm .
30.7k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
asked Jun 4, 2011 at 14:28
21.4k 3 3 gold badges 16 16 silver badges 5 5 bronze badges
I was point out that even a more correct way of updating npm is to use nodesource.com See stackoverflow.com/a/24760147/544463
Mar 28, 2015 at 21:02
Possible duplicate of How to update npm
Aug 19, 2016 at 13:18
@Motocarota Look at the dates, other question is duplicated of this one.
Feb 23, 2017 at 16:21
there is the tool nvm wich gives you the option to have more than one running versions of node+npm
Nov 7, 2017 at 13:24
Things have changed for the better since this was first asked (if you don't need version managemenent). See Update Node (Windows, Mac & Linux).
Nov 22, 2017 at 10:52
65 Answers 65
npm update -g npm
See the documentation for the update command:
npm update [-g] [. ]
This command will update all the packages listed to the latest version (specified by the tag config), respecting semver.
Additionally, see the documentation on Node.js and NPM installation and Upgrading NPM.
The following original answer is from the old FAQ that no longer exists, but it should work for Linux and Mac:
How do I update npm?
npm install -g npm
Please note that this command will remove your current version of npm. Make sure to use sudo npm install -g npm if on a Mac.
You can also update all outdated local packages by doing npm update without any arguments, or global packages by doing npm update -g .
Occasionally, the version of npm will progress such that the current version cannot be properly installed with the version that you have installed already. (Consider, if there is ever a bug in the update command.) In those cases, you can do this:
curl https://www.npmjs.com/install.sh | sh
To update Node.js itself, I recommend you use nvm, the Node Version Manager.
30.7k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Jun 4, 2011 at 14:48
110k 31 31 gold badges 163 163 silver badges 175 175 bronze badges
npm update npm -g didn't work for me on windows - it completed without output but npm remained the same version (1.3.11 when the most recent version is 1.3.14)
Nov 16, 2013 at 20:24
also have curl follow redirects with -L curl -L https://npmjs.org/install.sh | sudo sh
Apr 15, 2014 at 20:03
I did it like you said npm update npm -g and now I don't have npm as a command.
Jun 23, 2014 at 17:23
Using npm to install a new version of itself. I smell things blowing up.
Jan 26, 2016 at 4:53
DON'T use sudo npm install -g npm! This will uninstall it!
Oct 16, 2016 at 17:47
I found this really neat way of updating Node.js on David Walsh's blog. You can do it by installing n :
sudo npm cache clean -f sudo npm install -g n sudo n stable
It will install the current stable version of Node.js.
But please don't use n anymore. I recommend using nvm . You can simply install stable by following the commands below:
nvm ls-remote nvm install nvm use
30.7k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Jun 13, 2013 at 20:38
5,531 1 1 gold badge 15 15 silver badges 11 11 bronze badges
Refuses to run for windows x64 (but does with win32 apparently). That's not in keeping with the Node.js project.
Jan 29, 2015 at 0:10
Not supported for Windows. I realize it would be easier to just use Linux, but at work, I am not free to choose my OS. As @rainabba says, the spirit of the Node.js project is to be cross-platform, and this isn't.
Nov 5, 2015 at 19:04
In Windows, you can simply download the newest version of node and install it. It'll upgrade both node and npm.
Dec 17, 2015 at 22:13
Why did you said 'Please don't use n anymore' ? Any particular reason ?
Jan 16, 2019 at 4:59
I do not know why David Walsh said n was unstable at the time, but that blog was from six years ago and n is still being maintained. Repeating other commenters, n does not run on Windows. And neither does nvm .
Feb 16, 2019 at 22:57
Updating npm is easy:
npm install npm@latest -g
answered Mar 13, 2015 at 1:09
7,061 2 2 gold badges 20 20 silver badges 32 32 bronze badges
This causes fatal error, at least for mac users see here
Oct 18, 2015 at 22:26
Using windows 10 and node v5.7.0 the command npm install npm@latest -g failed to upgrade from npm 2.7.4 to npm 3.9.3.
May 31, 2016 at 19:00
Thanks this worked for me, its pretty simple. But i had to sudo npm install npm@latest -g thats all. Upvoted
Aug 9, 2016 at 7:21
This is also the official answer: docs.npmjs.com/getting-started/installing-node
Mar 20, 2017 at 23:16
Quit the terminal where you run the npm install -g npm and retry
Apr 3, 2021 at 9:31
I understand this question is for a Linux machine, but just in case anybody is looking for a Windows solution, just go to the Node.js site, click the download button on the homepage and execute the installer program.
Thankfully, it took care of everything, and with a few clicks of the Next button, I got the latest 0.8.15 Node.js version running on my Windows 7 machine.
30.7k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Dec 7, 2012 at 20:25
Anmol Saraf Anmol Saraf
15.1k 10 10 gold badges 52 52 silver badges 60 60 bronze badges
yeah. this worked for me. Im on windows. the n method didnt work. wish there was a better way of doing it.
Jun 19, 2013 at 21:19
This is the best and easiest way to upgrade node on windows. worked for me just fine. Thanks anmol
Oct 31, 2013 at 5:01
if you're updating from npm v1.x to 2.x on Windows, you may have delete ‘npm’, ‘npm.cmd’ files from “C:\Program Files\nodejs” after installing or udpating npm. See: escapologist.wordpress.com/2014/09/29/…
Feb 5, 2015 at 15:08
Don't forget to reboot afterwards!
Oct 19, 2015 at 8:41
This works with Windows 10, and both Node and npm update. Very slick.
Apr 28, 2016 at 18:13
As you may already know, npm is currently bundled with Node.js. It means that if you have installed Node.js, you've already installed npm as well.
Also, pay attention to the Node.js and npm release versions table that shows us approximate versions compatibility. Sometimes, versions discrepancy may cause incompatibility errors.
So, if you're a developer, it's kind of "best practice" to manage your development environment using one of the Node.js version managers.
Here is a list and usage notes of some of the most popular:
Homebrew (macOS)
If you're on macOS, you can use Homebrew.
Actually, it's not just a Node.js version manager.
To install Homebrew to your Mac:
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
To install Node.js and npm using Homebrew, run:
brew install node
Later, you will be able to update them using:
brew update && brew upgrade node
Also, you can switch between Node.js versions as well:
brew switch node 0.10.26
npm will be upgraded/downgraded automatically.
n (macOS, Linux)
n is most likely to rvm (Ruby Version Manager), and is used to manage Node.js and npm versions simultaneously. It is written on pure Linux shell, and available as an npm module. So, if you already have any Node.js version installed, you can install/update the n package through npm:
npm install -g n
Downloading, installing and switching to Node.js and npm versions is as easy as:
n 0.10.26 n 0.8.17 n 0.9.6
To download, install, and switch to the latest official release, use:
n latest
To download, install, and switch to the latest stable official release, use:
n stable
To switch to the previously active version (aka $ cd - ), use:
n prev
If you want to see the list of installed Node.js versions, just run n from your command line. The output will be something like the following:
0.10.26 • 0.8.17 0.9.6
Where the dot (•) means that it's a currently active version. To select another Node.js version from the list, use Up / Down arrow keys and activate using the Enter key.
To list the versions available to install:
n lsr
nvm (macOS, Linux)
nvm is also like rvm, even the command names and usage are very similar.
To install nvm, you can use the installation script (requires Git) using cURL :
curl https://raw.github.com/creationix/nvm/master/install.sh | sh
wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
To download and install a specific Node.js and npm version, use:
nvm install 0.10
Then, you can switch to the installed version, using:
nvm use 0.10
Also, you can create the .nvmrc file containing the version number, then switch to the specified version using the following command:
nvm use
To see the list of installed Node.js versions, use:
nvm ls
To list the versions available to install:
nvm ls-remote
nvm-windows (Windows)
nvm-windows is a Node.js version management utility for Windows, ironically written in Go.
It is not the same thing as nvm. However, the usage as a Node.js version manager is very similar.
To install nvm-windows, it is required to uninstall any existing versions of Node.js and npm beforehand. Then, download and run the latest installer from releases.
To upgrade nvm-windows, run the new installer. It will safely overwrite the files it needs to update without touching your Node.js installations.
nvm-windows runs in an Admin shell. You'll need to start PowerShell or Command Prompt as Administrator to use nvm-windows.
Before using, you may also need to enable nvm-windows with the following command:
nvm on
To download and install a specific Node.js and npm version, use:
nvm install 0.12
Then, you can switch to the installed version, using:
nvm use 0.12
If you want to see the list of installed Node.js versions, use:
nvm list
To list the versions available to install:
nvm list available
30.7k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Mar 7, 2014 at 15:45
5,924 2 2 gold badges 29 29 silver badges 34 34 bronze badges
I like this answer. +1 ! But it would have been even more useful to accompany it with some sort of explanation about the different package managers. Ie; why I should use one over the other. I would really help to give context..
Oct 19, 2015 at 5:01
with command "brew update && brew upgrade node" , npm doesn't get updated to latest version as mentioned ". NPM will be updated as well.."
Feb 24, 2017 at 10:36
I generally like homebrew but the fact it requires an update before I can upgrade npm on it is painfully slow.
Dec 26, 2018 at 18:43
can you please explain "npm will be upgraded/downgraded automatically." which command does this ?
Aug 17, 2020 at 5:52
First check your NPM version
npm -v
1) Update NPM to current version:
View curent NPM version:
npm view npm version
Update npm to current version:
npm i -g npm
2) List all available NPM versions and make a custom install/update/roll-back
View all versions including "alpha", "beta" and "rc" (release candidate)
npm view npm versions --json
Reinstall NPM to a specific version chosen from the versions list - for example to 5.0.3
- Installing one version will automatically remove the one currently installed.
- For Linux and iOS prepend commands with sudo
820 3 3 gold badges 15 15 silver badges 29 29 bronze badges
answered Jun 7, 2017 at 21:51
17.6k 6 6 gold badges 90 90 silver badges 87 87 bronze badges
I ran into bundle of errors including Error: EACCES: permission denied, unlink running above command with sudo worked
Oct 23, 2017 at 12:17
@DevWL, I'm trying your solution now. When I ran the npm view npm versions --json command, I got a TON of listings of versions beginning at "1.4.26" - "7.0.0-beta.12" so I'm running npm i -g [email protected] -- it appears to be taking a while (currently fetch -> lock is running but looks hung) fingers-crossed
Sep 27, 2020 at 12:44
Upgrading for Windows Users
Windows users should read Troubleshooting > Upgrading on Windows in the npm wiki.
Upgrading on windows 10 using PowerShell (3rd party edit)
The link above Troubleshooting#upgrading-on-windows points to a github page npm-windows-upgrade the lines below are quotes from the readme. I successfully upgraded from npm 2.7.4 to npm 3.9.3 using node v5.7.0 and powershell (presumably powershell version 5.0.10586.122)
First, ensure that you can execute scripts on your system by running the following command from an elevated PowerShell. To run PowerShell as Administrator, click Start, search for PowerShell, right-click PowerShell and select Run as Administrator.
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
Then, to install and use this upgrader tool, run (also from an elevated PowerShell or cmd.exe):
npm install --global --production npm-windows-upgrade npm-windows-upgrade
5,579 7 7 gold badges 50 50 silver badges 81 81 bronze badges
answered Dec 1, 2014 at 19:29
7,260 3 3 gold badges 53 53 silver badges 56 56 bronze badges
or just run: npm install -g npm
Mar 22, 2016 at 9:38
No Gal, you are confusing the issue, running npm install -g npm does not work on Windows, have you read the issues Windows users have had (listed above ?). Use the Powershell method as shown in Surf's answer. Thanks smurf , finally managed to upgrade yeeehaaaa!
Aug 3, 2016 at 9:02
First update npm ,
npm install -g npm@next
Then update node to the next version,
npm install -g node@next or npm install -g n@next or, to the latest,
npm install -g node@latest or npm install -g node
check after version installation,
node --version or node -v
26 1 1 silver badge 7 7 bronze badges
answered Dec 20, 2017 at 15:37
5,523 4 4 gold badges 29 29 silver badges 39 39 bronze badges
SIMPLY USE THIS
npm i -g npm
This is what i get promped on my console from npm when new update/bug-fix are released:

answered Jun 7, 2017 at 3:17
17.6k 6 6 gold badges 90 90 silver badges 87 87 bronze badges
after I ran this I had to exit the bash terminal and restart to see the changes. Because the path to npm changed during the update process and for some reason it kept executing the old version which showed the older version of course when you executed npm -v
Jul 9, 2018 at 0:22
- To update Node.js, use nvm (or nvmw for Windows).
- To update npm, the npm update npm -g command didn't work for me (on Windows). What did work was reinstalling npm according to the documentation: "You can download a ZIP file from https://npmjs.org/dist/, and unpack it in the same folder where node.exe lives." Make sure if you do this that you get rid of your previous installation first (though overwriting it will probably work ok. ).
- To update your modules, use the npm update command
30.7k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Nov 16, 2013 at 20:28
58.2k 34 34 gold badges 191 191 silver badges 208 208 bronze badges
npm update npm -g worked for me. I run OSx, and have node installed via homebrew, however, brew upgrade node won't run if you already have the latest node version running, as I did. Piece o' cake.
Mar 1, 2015 at 17:09
npm install -g npm@latest worked for me on Windows8 stackoverflow.com/a/29023180/588759
Apr 11, 2016 at 1:59
@rofrol I tried that command, it didn't work for me on Win 8.1. npm still had old version 3.8.0 even though my previous version was 6.10.x . I needed to upgrade npm to at least 6.11.x for Angular. Now I can't seem to get rid of the old version.
Sep 27, 2020 at 12:15
I think the best way to manage node.js is to use NVM. NVM stands for Node Version Manager.
It's a must-have tool for node.js developers!
You can install NVM using the following command, open terminal and run any one of the following:-
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
wget -qO- https://raw.githubusercontent.com/nvm-sh//nvm/v0.39.0/install.sh | bash
After installing this it's recommended to close the current terminal and open a new one since NVM will be adding some environment variables so terminal needs to be restarted.
I'll list down some of the basic commands for using NVM.
- This will fetch all the node versions from the internet. All node versions from beginning till date will be shown, It will also mention LTS versions alongside.
nvm ls-remote
- This will show you the recommended versions of npm and node you should use. (This works only if you already have a version of npm installed, if not use the above command)
npm doctor
- This will install the node version which you want (version list is obtained using the above command)
nvm install
for example nvm install v14.18.1
- This command will give us the list of node versions that are installed locally
nvm ls
- This command is used to remove the node version that you want from your computer
nvm uninstall v10.15.1
- The following command will help you upgrade to the latest working npm on the current node version
nvm install-latest-npm
- NVM can be used to manage multiple node versions simultaneously
- It can also help you install all the global npm packages from one version to another instead of manually installing each one of them!
- There are many other uses of nvm the details of which and the commands can be found here Node Version Manager
answered Feb 14, 2019 at 17:50
Viraj Shelke Viraj Shelke
778 9 9 silver badges 11 11 bronze badges
Thanks @lightwing for updating links! 🙂
Dec 11, 2021 at 7:29
Try the latest stable version of npm
See what version of npm you're running:
npm -v
Upgrading on *nix (OSX, Linux, etc.)
(You may need to prefix these commands with sudo , especially on Linux, or OS X if you installed Node using its default installer.)
You can upgrade to the latest version of npm using:
npm install -g npm@latest
Or upgrade to the most recent release:
npm install -g npm@next
Upgrading on Windows
By default, npm is installed alongside node in
C:\Program Files (x86)\nodejs
npm's globally installed packages (including, potentially, npm itself) are stored separately in a user-specific directory (which is currently
Because the installer puts
C:\Program Files (x86)\nodejs
on your PATH , it will always use the version of npm installed with node instead of the version of npm you installed using npm -g install npm@ .
To get around this, you can do one of the following:
- Option 1: edit your Windows installation's PATH to put %appdata%\npm before %ProgramFiles%\nodejs . Remember that you'll need to restart cmd.exe (and potentially restart Windows) when you make changes to PATH or how npm is installed.
- Option 2: remove both of
- %ProgramFiles%\nodejs\npm
- %ProgramFiles%\nodejs\npm.cmd
If you installed npm with the node.js installer, after doing one of the previous steps, do the following.
- Option 1 or 2
- Go into %ProgramFiles%\nodejs\node_modules\npm and copy the file named npmrc in the new npm folder, which should be %appdata%\npm\node_modules\npm . This will tell the new npm where the global installed packages are.
- Copy the npmrc file back into %ProgramFiles%\nodejs\node_modules\npm
A brief note on the built-in Windows configuration
The Node installer installs, directly into the npm folder, a special piece of Windows-specific configuration that tells npm where to install global packages. When npm is used to install itself, it is supposed to copy this special builtin configuration into the new install. There was a bug in some versions of npm that kept this from working, so you may need to go in and fix that up by hand. Run the following command to see where npm will install global packages to verify it is correct.
npm config get prefix -gIf it isn't set to :\Users\\AppData\Roaming\npm , you can run the below command to correct it:
npm config set prefix "$/npm" -gIncidentally, if you would prefer that packages not be installed to your roaming profile (because you have a quota on your shared network, or it makes logging in or out from a domain sluggish), you can put it in your local app data instead:
npm config set prefix "$/npm" -g. as well as copying %APPDATA%\npm to %LOCALAPPDATA%\npm (and updating your %PATH% , of course).
Everyone who works on npm knows that this process is complicated and fraught, and we're working on making it simpler. Stay tuned.
1 1 1 silver badge
answered Aug 8, 2018 at 0:08
Mohammad AlQanneh Mohammad AlQanneh
3,257 1 1 gold badge 16 16 silver badges 14 14 bronze badgesif devWL's solution doesn't work, I'm going to try yours. Thanks for the indepth answer. At this point, I'm wondering should I just uninstall Node and NPM -- it has taken me all day to try to fix this just so I can run Angular apps. I installed Node 12.18.4 today and thought it would update npm, but instead, when I run npm -v now, I get 3.8.0 as version when it previously was 6.10.x . Frustrating.
Sep 27, 2020 at 13:02
$ npm install -g npm stableWorked for me to update from 1.4.28 to 2.1.5
answered Oct 25, 2014 at 11:32
Arkadiusz Rosłaniec Arkadiusz Rosłaniec
221 2 2 silver badges 2 2 bronze badgesInstall npm => sudo apt-get install npm
Install n => sudo npm install n -g
latest version of node => sudo n latest
Specific version of node you can
List available node versions => n ls
Install a specific version => sudo n 4.5.0
774 1 1 gold badge 15 15 silver badges 29 29 bronze badges
answered May 26, 2017 at 11:22
Gurudath BN Gurudath BN
1,391 20 20 silver badges 21 21 bronze badgesTo install the latest version of npm using npm:
sudo npm install npm@latestI run this on Linux so I am not sure about other operating systems.
On Linux you can also run:
sudo apt-get update sudo apt-get upgradeThis will tell the apt-get package manager to update and upgrade all packages.
answered May 14, 2020 at 13:49
Justin Liu Justin Liu
591 6 6 silver badges 21 21 bronze badgesFor Linux users. To solve "Error: EACCES: permission denied", you can sudo command before running npm install. sudo npm i npm@latest
May 17, 2020 at 16:18
Or you can log in as root if you don't want to use sudo
May 25, 2020 at 14:57
You will typically want to npm install npm -g , right?
Oct 17, 2020 at 13:06I just installed Node.js on a new Windows 7 machine, with the following results:
> node -v v0.12.0 > npm -v 2.5.1I then did the above described procedure:
> npm install -g npmand it upgraded to v2.7.3. Except than doing npm -v still gave 2.5.1.
I went to the System configuration panel, advanced settings, environment variables. I saw a PATH variable specific to my user account, in addition to the global Path variable.
The former pointed to new npm: C:\Users\PhiLho\AppData\Roaming\npm
The latter includes the path to node: C:\PrgCmdLine\nodejs\ (Nowadays, I avoid to install stuff in Program Files and derivates. Avoiding spaces in paths, and noisy useless protections is saner. )
If I do which npm.cmd (I have Unix utilities installed. ), it points to the one in Node.Anyway, the fix is simple: I just copied the first path (to npm) just before the path to node in the main, global Path variable, and now it picks up the latest version.
;C:\Users\PhiLho\AppData\Roaming\npm;C:\PrgCmdLine\nodejs\> npm -v 2.7.3answered Mar 22, 2015 at 15:43
40.7k 6 6 gold badges 97 97 silver badges 135 135 bronze badges
did you put this as the last entry in your Environment Variables Path?
Sep 27, 2020 at 12:36@Chris22 It is not important, the important part is that the path to npm is before the path to nodejs. And, of course, you must have no other paths to identical names before these!
Oct 1, 2020 at 13:40
thanks. I'll keep this in mind. I still don't understand why when I installed node 12.x the other day, my npm version went backwards to 3.8.x when it was at version 6.x.x .
Oct 8, 2020 at 16:07
For Linux, OSX, etc..
To install the latest version of NPM
npm install -g npm@latest
Or To Install the most recent release
npm install -g npm@next
Additional : To check your npm version
If you are in a Windows Machine, I suggest going to the npm website
answered Sep 3, 2017 at 9:18
Abhishta Gatya Abhishta Gatya
883 2 2 gold badges 15 15 silver badges 32 32 bronze badges
What is the difference between the latest and the most recent?
Sep 13, 2017 at 18:49
@Chris Lang recent is the newest version but the latest is the newest stable version
Sep 17, 2017 at 5:29Just run the following command in terminal as root/administrator:
npm i -g n n stable npm update -g npmIt has worked for me on Linux
answered Nov 29, 2017 at 9:45
1,280 13 13 silver badges 24 24 bronze badgesYou could try this
npm install -g npm@latest
answered Mar 25, 2022 at 21:20
Samuel Reyes Samuel Reyes
177 1 1 silver badge 4 4 bronze badgesI recently stumbled across this article: http://martineau.tv/blog/2013/12/more-efficient-grunt-workflows/ and the author mentions npm-check-updates -u && npm install to update all dependencies.
30.7k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Jan 29, 2014 at 16:52
Jason Lydon Jason Lydon
7,104 2 2 gold badges 35 35 silver badges 44 44 bronze badges
david-dm.org And this just appeared as a comment from the post I cited. Seems perfect.
Jan 30, 2014 at 16:43
To be clear, npm-check-updates is another package that needs to be installed.
Apr 7, 2022 at 4:33
The link is broken: "404: NOT_FOUND"
Sep 1 at 14:13You can upgrade to the latest version of npm using:
npm install -g npm@latestanswered Jul 20, 2022 at 10:32
user15294241 user15294241npm install npm@ -gto update npm to the latest version:
npm install npm@latest -gand to check the version :
npm -vto update node js :
sudo npm cache clean -f sudo npm install -g n sudo n stablenode -vanswered Jun 5, 2017 at 9:14
Muhammad Habib Jawady Muhammad Habib Jawady
121 1 1 silver badge 2 2 bronze badgesSometimes it's just simpler to download the latest version from http://nodejs.org/
Especially when all other options fail.
http://nodejs.org/ -> click INSTALL -> you'll have the latest node and npm
answered Jun 27, 2014 at 22:47
5,115 1 1 gold badge 35 35 silver badges 28 28 bronze badgesDefinitely simpler, but doesn't always work. I've struggled with all of the above suggestion and some more - none worked on my mac. Going to nodejs.org fixed it.
Jun 28, 2014 at 20:51
in that case, you probably installed it in a bad way to begin with. Node/npm is one of those you want to prefix your installation so you don't need sudo for everything.
Aug 23, 2014 at 6:59
I probably installed it normally using brew or the installer. It might have been a specific bug in a specific npm version. I will probably never know and its probably doesn't matter - it was updating perfectly since than using npm update.
Aug 24, 2014 at 11:02
This worked for me, thanks. I was having issues getting to the latest, and screwed things up when I unknowingly emptied the npm cache, heh. Had to (re)install the msi (on Windows) to get fully updated. Worked perfectly.
Dec 1, 2014 at 21:38
If you're using OS X or Windows, the best way to install or update Node.js and npm is to use one of the installers from the Node.js download link , when I were downloaded and extracted, it simply updated node and npm version on my macbook pro os x 10.13.
Oct 18, 2017 at 2:37
Just listened to an interview with the npm team on the latest episode of nodeup, and they recommended not using update for the update from 1.x to 2.x . Instead, use: npm install npm -g
answered Oct 20, 2014 at 6:29
Nick Benes Nick Benes
1,334 15 15 silver badges 14 14 bronze badgesJust with this code
npm install updateanswered Nov 30, 2015 at 16:05
149 2 2 silver badges 4 4 bronze badgesWhen it comes to Linux I suggest an Update Node Using a Package Manager:
Node comes with npm pre-installed, but the manager is updated more frequently than Node. Run npm -v to see which version you have, then npm install npm@latest -g to install the newest npm update. Run npm -v again if you want to make sure npm updated correctly.
To update NodeJS , you’ll need npm’s handy n module. Run this code to clear npm’s cache, install n, and install the latest stable version of Node :
sudo npm cache clean -f sudo npm install -g n sudo n stableTo install the latest release, use n latest . Alternatively, you can run n #.#.# to get a specific Node version.
When it comes to Windows/ macOS I suggest using Installers on Nodejs.org
The Node.js downloads page includes binary packages for Windows and macOS — but why make your life more difficult? The pre-made installers — .msi for Windows and .pkg for macOS — make the installation process unbelievably efficient and understandable. Download and run the file, and let the installation wizard take care of the rest. With each downloaded update, the newer versions of Node and npm will replace the older version.
Alternatively, macOS users can use the npm and n instructions above.
When it comes to updating your node_modules dependencies folder, I suggest skipping all the things that could cause you a headache and just go to your specific project and re-run npm install again.
Before anyone does that, I suggest first checking your package.json file for the following:
As a user of NodeJS packages, you can specify which kinds of updates your app can accept in the package.json file. For example, if you were starting with a package version 1.0.4, this is how you could specify the allowed update version ranges in three basic ways:
To Allow Patch Releases: 1.0 or 1.0.x or ~1.0.4
To Allow Minor Releases: 1 or 1.x or ^1.0.4
To Allow Major Releases: * or xMAJOR version for when there are incompatible API changes. --> ~
MINOR version for when functionality is added in a backwards compatible manner. --> ^
PATCH version for when backward compatible bug fixes are done. --> *
