How to install node js ubuntu

How to install node js ubuntu

How To Install Node.js on Ubuntu 22.04

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Introduction

Node.js is a JavaScript runtime for server-side programming. It allows developers to create scalable backend functionality using JavaScript, a language many are already familiar with from browser-based web development.

In this guide, we will show you three different ways of getting Node.js installed on an Ubuntu 22.04 server:

For many users, using apt with the default repo will be sufficient. If you need specific newer (or legacy) versions of Node, you should use the PPA repository. If you are actively developing Node applications and need to switch between node versions frequently, choose the nvm method.

Prerequisites

This guide assumes that you are using Ubuntu 22.04. Before you begin, you should have a non-root user account with sudo privileges set up on your system. You can learn how to do this by following the Ubuntu 22.04 initial server setup tutorial.

Option 1 — Installing Node.js with Apt from the Default Repositories

Ubuntu 22.04 contains a version of Node.js in its default repositories that can be used to provide a consistent experience across multiple systems. At the time of writing, the version in the repositories is 12.22.9. This will not be the latest version, but it should be stable and sufficient for quick experimentation with the language.

Warning: The version of Node.js included with Ubuntu 22.04, version 12.22.9, is an LTS, or “long-term support” release. It is technically outdated, but should be supported until the release of Ubuntu 24.04.

To get this version, you can use the apt package manager. Refresh your local package index first by typing:

Then install Node.js:

PressВ Y В when prompted to confirm installation. If you are prompted to restart any services, pressВ ENTER В to accept the defaults and continue. Check that the install was successful by querying node for its version number:

This will allow you to install modules and packages to use with Node.js.

At this point you have successfully installed Node.js and npm using apt and the default Ubuntu software repositories. The next section will show how to use an alternate repository to install different versions of Node.js.

Option 2 — Installing Node.js with Apt Using a NodeSource PPA

To install a different version of Node.js, you can use a PPA (personal package archive) maintained by NodeSource. These PPAs have more versions of Node.js available than the official Ubuntu repositories. Node.js v14, v16, and v18 are available as of the time of writing.

First, we will install the PPA in order to get access to its packages. From your home directory, use curl to retrieve the installation script for your preferred version, making sure to replace 18.x with your preferred version string (if different).

Refer to the NodeSource documentation for more information on the available versions.

You can inspect the contents of the downloaded script with nano (or your preferred text editor):

Running third party shell scripts is not always considered a best practice, but in this case, NodeSource implements their own logic in order to ensure the correct commands are being passed to your package manager based on distro and version requirements. If you are satisfied that the script is safe to run, exit your editor, then run the script with sudo :

At this point you have successfully installed Node.js and npm using apt and the NodeSource PPA. The next section will show how to use the Node Version Manager to install and manage multiple versions of Node.js.

Option 3 — Installing Node Using the Node Version Manager

Another way of installing Node.js that is particularly flexible is to use nvm, the Node Version Manager. This piece of software allows you to install and maintain many different independent versions of Node.js, and their associated Node packages, at the same time.

To install NVM on your Ubuntu 22.04 machine, visit the project’s GitHub page. Copy the curl command from the README file that displays on the main page. This will get you the most recent version of the installation script.

Take a look and make sure you are comfortable with the changes it is making. When you are satisfied, run the command again with | bash appended at the end. The URL you use will change depending on the latest version of nvm, but as of right now, the script can be downloaded and executed by typing:

Now, you can ask NVM which versions of Node are available:

It’s a very long list! You can install a version of Node by typing any of the release versions you see. For instance, to get version v16.14.0 (another LTS release), you can type:

You can see the different versions you have installed by typing:

You can verify that the install was successful using the same technique from the other sections, by typing:

The correct version of Node is installed on our machine as we expected. A compatible version of npm is also available.

Conclusion

There are quite a few ways to get up and running with Node.js on your Ubuntu 22.04 server. Your circumstances will dictate which of the above methods is best for your needs. While using the packaged version in Ubuntu’s repository is the easiest method, using nvm or a NodeSource PPA offers additional flexibility.

For more information on programming with Node.js, please refer to our tutorial series How To Code in Node.js.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Установка Node.js в Ubuntu 20.04

Для платформы уже создано более чем миллион пакетов, которыми можно управлять с помощью менеджера пакетов Node или NPM. Это отличная система для расширяемости приложения с помощью решений с открытым исходным кодом. В этой статье мы рассмотрим четыре способа установить Node.js в Ubuntu 20.04. Мы рассмотрим их все ниже, но рекомендуется использовать первый:

Первый способ рекомендованный, но второй более простой, третий и четвертый позволяют получить более новые версии программ. Если у вас уже была установлена более старая версия Node js, ее нужно удалить, чтобы не возникало конфликтов, также вы можете просто обновить программу, для этого смотрите статью как обновить Node.js на Windows, Linux и Mac.

Удалить старую версию Node.js

Сначала давайте проверим установлена ли у вас эта программа:

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

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

sudo apt purge nodejs

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Теперь можно переходить к рассмотрению того как установить 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 можно с помощью следующей команды:

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

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

Затем смотрим список доступных версий Node js:

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

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

nvm install 14.0

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

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

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Дальше необходимо указать менеджеру какую версию нужно использовать:

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

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Чтобы удалить эту версию node js, ее нужно деактивировать:

nvm deactivate 14.0

Затем можно удалить:

nvm uninstall 14.0

Установка Node.js из репозиториев Ubuntu

Это самый простой способ установки этой платформы. Сначала выполните команду:

sudo apt install nodejs

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Затем установите менеджер пакетов npm:

sudo apt install npm

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

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Как видите, при использовании официальных репозиториев вы получаете более старую версию.

Установка Node js из PPA

Установка Node js Ubuntu из PPA, это альтернативный вариант, позволяющий получить более новую версию, достаточно простым способом. Сначала добавьте репозитории Node js в список репозиториев Ubuntu с помощью такой одной из следующих команд. Для установки самой последней версии выполните:

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

А для стабильной:

Затем просто установите программу с помощью пакетного менеджера:

sudo apt install nodejs

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

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

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Установка Node js из бинарников

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

Чтобы узнать архитектуру выполните:

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

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

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Вы можете скачать Node js и с помощью терминала, например, эта команда для 64 бит версии:

Теперь распаковываем бинарные файлы программы:

Смотрим версию, чтобы убедится, что все работает:

Как установить Node.js в Ubuntu 20.04

Вступление

Node.js — основанная на javascript-движке V8 от Google серверная среда выполнения javascript, ставшая в последние годы очень популярной. Первый ее выпуск датируется 2010 годом. За это время Node.js прошла путь от смелого эксперимента к одному из лидеров рынка, который поддерживается Microsoft, Google, IBM, linkedIn, NASA и многими другими.

На Node.js основан Electron — фреймворк, который применяется в разработке десктопных приложений на javascript.

Все это делает javascript, на котором и базируется Node.js, универсальным языком. Конечно, как и у любого универсального решения, у него есть свои недостатки. Он однопоточный, хоть и асинхронный. У него относительно низкая производительность из-за особенностей архитектуры. «Числодробилки» на нем точно писать не стоит. Зато его конек — фронтенд (вне конкуренции по причине отсутствия конкуренции) и быстрое прототипирование сервисов для proof of concept — проверки концепции на жизнеспособность. Часто Node.js-микросервисы используются как прокси для других микросервисов.

Управлять зависимостями очень легко с помощью npm. Для того, получить какой-то модуль в свой проект, можно просто сделать:

А дальше подключить его в своем приложении. Npm входит в Node.js, так что, в большинстве случаев установка npm на наш Ubuntu не требуется.

Несмотря на то, что сборки Node.js есть под огромное число платформ, лучшим выбором будет установка Node.js на linux.

В этом руководстве мы расскажем как установить Node.js на сервер под управлением Ubuntu 20.04.

Перед установкой — подготовить сервер

Залогинимся в личном кабинете https://my.selectel.ru/login/, нажав на вкладку «Облачная платформа». Там вы сможете создать виртуальный сервер.

Необходимо выбрать зону размещения сервера исходя из его близости к пользователям. Пинг выше, если сервер дальше.

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Нажмем «Создать сервер».

В разделе «Источник» убеждаемся, что выбран образ Ubuntu 20.04.

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Конфигурацию можно настроить по своим потребностям.

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

В разделе «Сеть» стоит выбрать «Подсеть — Плавающий IP-адрес».

В разделе «Доступ» загрузите SSH-ключ и не забудьте сохранить root-пароль. Подробнее об этом рассказано в этой статье.

Теперь можно создать сервер кнопкой «Создать» в самом низу.

Будет отображена страница статуса сервера, надо дождаться индикации ACTIVE вверху справа.

Теперь на вкладке «Порты» можно посмотреть IP-адрес, присвоенный серверу.

Облачные серверы

Удаление старых версий

Если у вас уже был готовый сервер, то на нем, возможно, присутствуют старые версии. Их стоит удалить во избежание конфликтов, которые бывает крайне сложно отследить в дальнейшем. При создании сервера несколько минут назад, можно сразу начать установку, иначе надо проверить предыдущие инсталляции Node.js:

В ответ на команду могут появиться пакеты/пакет, их можно удалить:

Способ №1: NVM

Для управления установленной версией Node.js и внесения изменений необходима утилита NVM (Node Version Manager). Она будет приоритетна для работы на локальной машине разработчика, для dev-систем и тестирования новых фич в экспериментальных версиях. Возможность быстро сменить версию может очень пригодиться во всех этих вариантах. NVM на Ubuntu устанавливается без проблем. Приступим к установке.

Сперва зададим команду сбора списка пакетов из репозиториев:

Некоторые версии Node.js нужно собирать, поэтому нужные для этого пакеты важно установить:

Если требуется установка или обновление NVM, команда должна выглядеть так:

Убедитесь в актуальности устанавливаемых версий. Вся информация есть в официальном репозитории NVM.

Как только установка завершится, необходимо осуществить перезапуск сессии (переподключиться или перелогиниться), или задать команду:

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

Список большой, так как Node.js существует с 2010 года и какое-то время даже существовала двумя параллельными проектами, которые через какое-то время снова слились в один проект.
Для знакомства с серверной средой Node.js стоит выбрать LTS. Она будет отмечена в списке соответствующим комментарием.

Вы можете установить любую нужную вам версию, например, нам нужна 14.16.1.

Обратите внимание на строку Now using node v14.16.1 (npm v6.14.12) при установке, эта версия сразу становится активной.

Если вы захотите посмотреть версии, которые установили, это легко сделать с помощью команды:

Если вы хотите сделать активной какую-то другую версию, укажите команду:

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

Перед удалением определенной версии надо сначала ее деактивировать:

А потом удалить командой:

В системе ее больше не видно.

Способ №2: репозитории Ubuntu

Самый простой способ установки Node.js на Ubuntu 20.04. Использовать в production не рекомендуется, но для знакомства, можно использовать.

Сначала обновляем список пакетов, доступных к установке:

Теперь устанавливаем Node.js:

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

Обратите внимание, что хоть способ установки и прост, версия очень старая. Для боевых целей вам этот вариант не подойдет. Он больше подходит для новичков, которые только начинают знакомиться с Node.js. Об актуальных версиях серверной среды от Google мы рассказали в способах установки NVM и из официального репозитория.

Способ №3: Установка из официального репозитория Node.js (PPA)

Для production-систем лучше использовать официальные репозитории Node.js, они есть для всех популярных linux-дистрибутивов. Репозиторий позволит буквально двумя командами обновиться до актуальной версии вместе со всей системой.

В этой инструкции вы найдете специальный скрипт. Он поможет с добавлением репозитория в систему:

Следующий шаг — выполнение команды установки Node.js:

В скрипте также указано, что для сборки некоторых пакетов npm, стоит установить gcc, g++ и make:

Способ №4: Установка из бинарных файлов

Этот способ довольно редкий, он применим для уникальных ситуаций. Например, в подготовке embedded, т.е. встроенной системы без доступа к ней снаружи для администрирования.
В остальных случаях — в этому способу стоит относиться с осторожностью во избежание проблем с обновлениями и управлением зависимостями.

Кроме того, такую установку очень сложно отменить, ее следы могут остаться в системе навсегда.

Сперва узнаем, какая архитектура у вашей системы:

На официальном сайте нужно выбрать версию и архив для архитектуры.

В нашем случае команда на скачивание:

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

Все готово, дальше — обновить npm

Node.js установлен, пора приступать к его использованию. Перед этим стоит обновить ваш пакетный менеджер npm. Как правило, версия пакетного менеджера довольно устаревшая.

Смотрим, какая версия установлена сейчас:

Теперь можем создать первое приложение, чтобы убедиться в работоспособности инсталляции.

Сначала создаем ему директорию:

Без использования ключа -y вам будет задано несколько вопросов о названии проекта, авторе, лицензии, репозитории и так далее. Команда создала в директории файл package.json, который является описанием всего проекта. Там прописываются зависимости, метаинформация, скрипты запуска, тестов и сборки проекта и так далее.

Теперь установим какую-нибудь библиотеку из npmjs.com, например, пакет ip. Этот пакет позволяет удобно работать с IP-адресами.

Ключ -s указывает npm сохранить пакет как зависимость в package.json. Без него пакет будет установлен, но не будет запомнен в рамках проекта.

Создадим ваше первое приложение:

И вставим вот эту программу в файл:

Сохраняем (CTRL + O), закрываем (CTRL + X) nano. Запускаем первую программу:

How To Install Node.js on Ubuntu 18.04

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Introduction

Node.js is a JavaScript platform for general-purpose programming that allows users to build network applications quickly. By leveraging JavaScript on both the front and backend, Node.js makes development more consistent and integrated.

In this guide, you’ll learn about three different methods to install Node.js on an Ubuntu 18.04 server.

Prerequisites

This guide assumes that you are using Ubuntu 18.04. Before you begin, you should have a non-root user account with sudo privileges set up on your system. You can learn how to do this by following the initial server setup tutorial for Ubuntu 18.04.

Installing Node.js from Default Repositories with Apt

Ubuntu 18.04 contains a version of Node.js in its default repositories that can be used to provide a consistent experience across multiple systems. At the time of writing, the version in the repositories is 8.10.0. This will not be the latest version, but it should be stable and sufficient for quick experimentation with the language.

To get this version, you can use the apt package manager. Refresh your local package index:

Now install Node.js:

Verify you’ve installed Node.js successfully by querying node for its version number:

This will allow you to install modules and packages to use with Node.js.

You’ve now successfully installed Node.js and npm using apt and the default Ubuntu software repositories. However, you may prefer to work with different versions of Node.js, package archives, or version managers. The next steps will discuss these elements, along with more flexible and robust methods of installation.

Installing Node.js with Apt Using a NodeSource PPA

To install a more recent version of Node.js you can add the PPA (personal package archive) maintained by NodeSource. This will have more up-to-date versions of Node.js than the official Ubuntu repositories and will allow you to choose between several available versions of the platform.

First, install the PPA in order to get access to its contents. From your home directory, use curl to retrieve the installation script for your preferred version, making sure to replace 17.x with your preferred version string (if different):

You can refer to the NodeSource documentation for more information on currently available versions.

If you’d like, you can inspect the contents of this script with nano (or your preferred text editor):

The PPA will be added to your configuration and your local package cache will be updated automatically. Now you can install the Node.js package as you did in the previous section:

In order for some npm packages to work (those that require compiling code from source, for example), you need to install the build-essential package:

Now you have the necessary tools to work with npm packages that require compiling code from source.

In this section, you successfully installed Node.js and npm using apt and the NodeSource PPA. Next, you’ll use the Node Version Manager to install and manage multiple versions of Node.js.

Installing Node Using the Node Version Manager

To install NVM on your Ubuntu 18.04 machine, visit the project’s GitHub page. Copy the curl command from the README file that displays on the main page to get the most recent version of the installation script.

Review the output and make sure you are comfortable with the changes it is making. Once you’re satisfied, run the same command with | bash appended at the end. The URL you use will change depending on the latest version of NVM, but as of right now, the script can be downloaded and executed by running the following:

With nvm installed, you can install isolated Node.js versions. First, ask nvm what versions of Node are available:

It’s a very long list, but you can install a version of Node by inputting any of the released versions listed. For example, to get version v16.13.1, run the following:

Sometimes nvm will switch to use the most recently installed version. But you can tell nvm to use the version you just downloaded (if different):

Check the version currently being used by running the following:

If you have multiple Node versions installed, you can run ls to get a list of them:

You can also default to one of the versions:

This version will be automatically selected when a new session spawns. You can also reference it by the alias like in the following command:

Each version of Node will keep track of its own packages and has npm available to manage these.

This will install the package in:

Installing the module globally will let you run commands from the command line, but you’ll have to link the package into your local sphere to require it from within a program:

You can learn more about the options available to you with nvm by running the following:

Removing Node.js

If you don’t want to save the configuration files for later use, then run the following command to uninstall the package and remove the configuration files associated with it:

As a final step, you can remove any unused packages that were automatically installed with the removed package:

If the version you are targeting is not the current active version, you can run:

This command will uninstall the selected version of Node.js.

If the version you would like to remove is the current active version, you must first deactivate nvm to enable your changes:

Now you can uninstall the current version using the uninstall command used previously. This removes all files associated with the targeted version of Node.js except the cached files that can be used for reinstallment.

Conclusion

There are quite a few ways to get up and running with Node.js on your Ubuntu 18.04 server. Your circumstances will dictate which of the methods is best for your needs. While using the packaged version in Ubuntu’s repository is one method, using nvm or a NodeSource PPA offers additional flexibility.

For more information on programming with Node.js, please refer to our tutorial series How To Code in Node.js.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

How To Install Node.js on Ubuntu 20.04

How to install node js ubuntu. Смотреть фото How to install node js ubuntu. Смотреть картинку How to install node js ubuntu. Картинка про How to install node js ubuntu. Фото How to install node js ubuntu

Introduction

Node.js is a JavaScript runtime for server-side programming. It allows developers to create scalable backend functionality using JavaScript, a language many are already familiar with from browser-based web development.

In this guide, we will show you three different ways of getting Node.js installed on an Ubuntu 20.04 server:

For many users, using apt with the default repo will be sufficient. If you need specific newer (or legacy) versions of Node, you should use the PPA repository. If you are actively developing Node applications and need to switch between node versions frequently, choose the nvm method.

Prerequisites

This guide assumes that you are using Ubuntu 20.04. Before you begin, you should have a non-root user account with sudo privileges set up on your system. You can learn how to do this by following the Ubuntu 20.04 initial server setup tutorial.

Option 1 — Installing Node.js with Apt from the Default Repositories

Ubuntu 20.04 contains a version of Node.js in its default repositories that can be used to provide a consistent experience across multiple systems. At the time of writing, the version in the repositories is 10.19. This will not be the latest version, but it should be stable and sufficient for quick experimentation with the language.

Warning: the version of Node.js included with Ubuntu 20.04, version 10.19, is now unsupported and unmaintained. You should not use this version in production, and should refer to one of the other sections in this tutorial to install a more recent version of Node.

To get this version, you can use the apt package manager. Refresh your local package index first by typing:

Then install Node.js:

Check that the install was successful by querying node for its version number:

This will allow you to install modules and packages to use with Node.js.

At this point you have successfully installed Node.js and npm using apt and the default Ubuntu software repositories. The next section will show how to use an alternate repository to install different versions of Node.js.

Option 2 — Installing Node.js with Apt Using a NodeSource PPA

To install a different version of Node.js, you can use a PPA (personal package archive) maintained by NodeSource. These PPAs have more versions of Node.js available than the official Ubuntu repositories. Node.js v12, v14, and v16 are available as of the time of writing.

First, we will install the PPA in order to get access to its packages. From your home directory, use curl to retrieve the installation script for your preferred version, making sure to replace 16.x with your preferred version string (if different).

Refer to the NodeSource documentation for more information on the available versions.

Inspect the contents of the downloaded script with nano (or your preferred text editor):

When you are satisfied that the script is safe to run, exit your editor, then run the script with sudo :

The PPA will be added to your configuration and your local package cache will be updated automatically. You can now install the Node.js package in the same way you did in the previous section:

At this point you have successfully installed Node.js and npm using apt and the NodeSource PPA. The next section will show how to use the Node Version Manager to install and manage multiple versions of Node.js.

Option 3 — Installing Node Using the Node Version Manager

Another way of installing Node.js that is particularly flexible is to use nvm, the Node Version Manager. This piece of software allows you to install and maintain many different independent versions of Node.js, and their associated Node packages, at the same time.

To install NVM on your Ubuntu 20.04 machine, visit the project’s GitHub page. Copy the curl command from the README file that displays on the main page. This will get you the most recent version of the installation script.

Take a look and make sure you are comfortable with the changes it is making. When you are satisfied, run the command again with | bash appended at the end. The URL you use will change depending on the latest version of nvm, but as of right now, the script can be downloaded and executed by typing:

Now, you can ask NVM which versions of Node are available:

It’s a very long list! You can install a version of Node by typing any of the release versions you see. For instance, to get version v14.10.0, you can type:

You can see the different versions you have installed by typing:

Additionally, you’ll see aliases for the various long-term support (or LTS) releases of Node:

You can switch between installed versions with nvm use :

The correct version of Node is installed on our machine as we expected. A compatible version of npm is also available.

Conclusion

There are a quite a few ways to get up and running with Node.js on your Ubuntu 20.04 server. Your circumstances will dictate which of the above methods is best for your needs. While using the packaged version in Ubuntu’s repository is the easiest method, using nvm or a NodeSource PPA offers additional flexibility.

For more information on programming with Node.js, please refer to our tutorial series How To Code in Node.js.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *