Как установить node js linux
Перейти к содержимому

Как установить node js linux

  • автор:

Installing Node.js via package manager

Note: The packages on this page are maintained and supported by their respective packagers, not the Node.js core team. Please report any issues you encounter to the package maintainer. If it turns out your issue is a bug in Node.js itself, the maintainer will report the issue upstream.

Alpine Linux

Node.js LTS and npm packages are available in the Main Repository.

Node.js Current can be installed from the Community Repository.

Android

Android support is still experimental in Node.js, so precompiled binaries are not yet provided by Node.js developers.

However, there are some third-party solutions. For example, Termux community provides terminal emulator and Linux environment for Android, as well as own package manager and extensive collection of many precompiled applications. This command in Termux app will install the last available Node.js version:

Currently, Termux Node.js binaries are linked against system-icu (depending on libicu package).

Arch Linux

Node.js and npm packages are available in the Community Repository.

CentOS, Fedora and Red Hat Enterprise Linux

Node.js is available as a module called nodejs in CentOS/RHEL 8 and Fedora.

where <stream> corresponds to the major version of Node.js. To see a list of available streams:

For example, to install Node.js 18:

For CentOS/RHEL 7 Node.js is available via Software Collections.

Alternatives

These resources provide packages compatible with CentOS, Fedora, and RHEL.

    maintained and supported at https://github.com/nodejs/snap maintained and supported by NodeSource

Debian and Ubuntu based Linux distributions

Alternatives

Packages compatible with Debian and Ubuntu based Linux distributions are available via Node.js snaps.

Fast and simple Node.js version manager built in Rust used to manage multiple released Node.js versions. It allows you to perform operations like install, uninstall, switch Node versions automatically based on the current directory, etc. To install fnm, use this install script.

fnm has cross-platform support (macOS, Windows, Linux) & all popular shells (Bash, Zsh, Fish, PowerShell, Windows Command Line Prompt). fnm is built with speed in mind and compatibility support for .node-version and .nvmrc files.

FreeBSD

The most recent release of Node.js is available via the www/node port.

Install a binary package via pkg:

Or compile it on your own using ports:

Gentoo

Node.js is available in the portage tree.

IBM i

LTS versions of Node.js are available from IBM, and are available via the 'yum' package manager. The package name is nodejs followed by the major version number (for instance, nodejs12 , nodejs14 etc)

To install Node.js 14.x from the command line, run the following as a user with *ALLOBJ special authority:

Node.js can also be installed with the IBM i Access Client Solutions product. See this support document for more details

macOS

Download the macOS Installer directly from the nodejs.org web site.

If you want to download the package with bash:

Alternatives

Using Homebrew:

Using MacPorts:

Using pkgsrc:

Install the binary package:

Or build manually from pkgsrc:

n is a simple to use Node.js version manager for Mac and Linux. Specify the target version to install using a rich syntax, or select from a menu of previously downloaded versions. The versions are installed system-wide or user-wide, and for more targeted use you can run a version directly from the cached downloads.

See the homepage for install methods (bootstrap, npm, Homebrew, third-party), and all the usage details.

If you already have npm then installing n and then the newest LTS node version is as simple as:

NetBSD

Node.js is available in the pkgsrc tree:

Or install a binary package (if available for your platform) using pkgin:

Nodenv

nodenv is a lightweight node version manager, similar to nvm . It's simple and predictable. A rich plugin ecosystem lets you tailor it to suit your needs. Use nodenv to pick a Node version for your application and guarantee that your development environment matches production.

Nodenv installation instructions are maintained on its Github page. Please visit that page to ensure you're following the latest version of the installation steps.

Node Version Manager is a bash script used to manage multiple released Node.js versions. It allows you to perform operations like install, uninstall, switch version, etc. To install nvm, use this install script.

On Unix / OS X systems Node.js built from source can be installed using nvm by installing into the location that nvm expects:

After this you can use nvm to switch between released versions and versions built from source. For example, if the version of Node.js is v8.0.0-pre:

Once the official release is out you will want to uninstall the version built from source:

Windows

The nvs version manager is cross-platform and can be used on Windows, macOS, and Unix-like systems

To install nvs on Windows go to the release page here and download the MSI installer file of the latest release.

You can also use chocolatey to install it:

macOS,UnixLike

You can find the documentation regarding the installation steps of nvs in macOS/Unix-like systems here

Usage

After this you can use nvs to switch between different versions of node.

To add the latest version of node:

Or to add the latest LTS version of node:

Then run the nvs use command to add a version of node to your PATH for the current shell:

To add it to PATH permanently, use nvs link :

OpenBSD

Node.js is available through the ports system.

Using pkg_add on OpenBSD:

openSUSE and SLE

Node.js is available in the main repositories under the following packages:

  • openSUSE Leap 15.2: nodejs10 , nodejs12 , nodejs14
  • openSUSE Tumbleweed: nodejs16
  • SUSE Linux Enterprise Server (SLES) 12: nodejs10 , nodejs12 , and nodejs14 (The "Web and Scripting Module" must be enabled.)
  • SUSE Linux Enterprise Server (SLES) 15 SP2: nodejs10 , nodejs12 , and nodejs14 (The "Web and Scripting Module" must be enabled.)

For example, to install Node.js 14.x on openSUSE Leap 15.2, run the following as root:

Different major versions of Node can be installed and used concurrently.

SmartOS and illumos

SmartOS images come with pkgsrc pre-installed. On other illumos distributions, first install pkgsrc, then you may install the binary package as normal:

Or build manually from pkgsrc:

Node.js snaps are available as node on the Snap store.

Solus

Solus provides Node.js in its main repository.

Void Linux

Void Linux ships Node.js stable in the main repository.

Windows

Download the Windows Installer directly from the nodejs.org web site.

Alternatives

Using Winget:

After running one of the two commands above, it may be necessary to restart the terminal emulator before the node CLI command becomes available.

“How to Install Node.js” and “npm” on “Ubuntu 20.04”

Maneesh kushwaha

Node.js is a cross-platform JavaScript runtime surroundings constructed on Chrome’s JavaScript, designed to execute JavaScript code on the server-side. It’s typically used to construct back-end purposes, however it is usually in style as a full-stack and front-end answer. npm is the default bundle supervisor for Node.js and the world’s largest software program registry.

On this tutorial, we are going to discover three alternative ways of putting in Node.js and npm on Ubuntu 20.04:

  • From the usual Ubuntu repositories. That is the best strategy to set up Node.js and npm on Ubuntu and ought to be adequate for many use instances. The model included within the Ubuntu repositories is 10.19.0 .
  • From the NodeSource repository. Use this repository if you wish to set up a special Node.js model than the one supplied within the Ubuntu repositories. At present, NodeSource helps Node.js v14.x , v13.x , v12.x , and v10.x .
  • Utilizing nvm (Node Model Supervisor). This device lets you have a number of Node.js variations put in on the identical machine. If you’re Node.js developer, then that is the popular manner of putting in Node.js.

Select the set up methodology that’s acceptable on your surroundings. If you’re unsure which Node.js model to put in, seek the advice of the documentation of the applying you’re going to deploy.

Set up Node.js and npm from the Ubuntu repository #

On the time of writing, the Node.js model included within the Ubuntu 20.04 repositories is 10.19.0 which is the earlier TLS model.

The set up is fairly easy. Run the next instructions to replace the bundle index and set up Node.js and npm:

The command above will set up plenty of packages, together with the instruments essential to compile and set up native addons from npm.

As soon as carried out, confirm the set up by operating:

Installing Node.js and npm from NodeSource #

NodeSource is an organization targeted on offering enterprise-grade Node help. It maintains an APT repository containing a number of Node.js variations. Use this repository in case your utility requires a selected model of Node.js.

On the time of writing, NodeSource repository supplies the next variations:

  • v14.x — The newest steady model.
  • v13.x
  • v12.x — The newest LTS model.
  • v10.x — The earlier LTS model.

We’ll set up Node.js model 14.x:

Run the next command as a person with sudo privileges to obtain and execute the NodeSource set up script:

The script will add the NodeSource signing key to your system, create an apt repository file, set up all obligatory packages, and refresh the apt cache. For those who want one other Node.js model, for instance 12.x , change the setup_14.x with setup_12.x .

As soon as the NodeSource repository is enabled, set up Node.js and npm:

The nodejs package contains both the node and npm binaries.

Verify that the Node.js and npm were successfully installed by printing their versions:

To be able to compile native addons from npm you’ll need to install the development tools:

Installing Node.js and npm using NVM #

NVM (Node Model Supervisor) is a bash script that lets you handle a number of Node.js variations on a per-user foundation. With NVM you’ll be able to set up and uninstall any Node.js model that you simply need to use or take a look at.

Go to the nvm GitHub repository web page and duplicate both the curl or wget command to obtain and set up the nvm script:

Do not use sudo as it will enable nvm for the root user.

The script will clone the project’s repository from Github to the

Because the output above says, it’s best to both shut and reopen the terminal or run the instructions so as to add the trail to nvm script to the present shell session. You are able to do no matter is simpler for you.

As soon as the script is in your PATH , confirm that nvm was correctly put in by typing:

To get a list of all Node.js versions that can be installed with nvm , run:

The command will print a huge list of all available Node.js versions.

To install the latest available version of Node.js, run:

The output should look something like this:

Once the installation is completed, verify it by printing the Node.js version:

Let’s install two more versions, the latest LTS version and version 10.9.0 :

You can list the installed Node.js versions by typing:

The output should look something like this:

The entry with an arrow on the precise ( > v10.9.0 ) is the Node.js model used within the present shell session and the default model is ready to v14.2.0 . Default model is the model that will likely be energetic when opening new shells.

If you wish to change the presently energetic model enter:

To change the default Node.js version, run the following command:

For extra detailed details about methods to use the nvm script, go to the venture’s GitHub web page.

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

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

Node.js — это среда выполнения JavaScript для программирования на стороне сервера. Она позволяет разработчикам создавать масштабируемый серверный функционал с помощью JavaScript, языка, который многим уже знаком по веб-разработке под браузер.

В этом обучающем модуле мы покажем вам три разных варианта установки Node.js на сервере Ubuntu 20.04:

  • использование apt для установки пакета nodejs из репозитория ПО Ubuntu по умолчанию
  • использование apt с альтернативным репозиторием ПО PPA для установки определенных версий пакета nodejs
  • установка диспетчера nvm (Node Version Manager) и его использование для установки нескольких версий node и управления ими

Для многих пользователей будет достаточно использовать apt с репозиторием по умолчанию. Если вам требуется определенная более новая (или старая) версия Node, вам следует использовать репозиторий PPA. Если вы занимаетесь активной разработкой приложений Node, и вам нужно часто переключаться между версиями node , используйте метод nvm .

Предварительные требования

Для целей этого обучающего модуля предполагается, что вы используете ОС Ubuntu 20.04. Для начала вам потребуется учетная запись пользователя без привилегий root с привилегиями sudo. Чтобы создать такую учетную запись следуйте указаниям обучающего модуля «Начальная настройка сервера Ubuntu 20.04».

Вариант 1 — Установка Node.js с помощью Apt из репозиториев по умолчанию

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

Для получения этой версии можно использовать диспетчер пакетов apt . Обновите указатель локальных пакетов с помощью следующей команды:

Выполните установку Node.js:

Проверьте, что установка выполнена успешно, запросив у node номер версии:

Если пакет из репозитория отвечает вашим потребностям, для начала работы с Node.js ничего больше не потребуется. В большинстве случаев также нужно установить npm , диспетчер пакетов Node.js. Для этого установите пакет npm с помощью apt :

Это позволит вам устанавливать модули и пакеты для использования с Node.js.

Вы успешно установили Node.js и npm , используя apt и репозитории ПО Ubuntu по умолчанию. В следующем разделе мы покажем, как использовать альтернативный репозиторий для установки разных версий Node.js.

Вариант 2 — Установка Node.js с помощью Apt через архив NodeSource PPA

Для установки другой версии Node.js вы можете использовать архив PPA (архив персональных пакетов), обслуживаемый NodeSource. Через PPA можно установить другие версии Node.js, кроме доступных в официальных репозиториях Ubuntu. На момент составления этого обучающего модуля доступны версии Node.js v10, v12, v13 и v14.

Вначале установим PPA для получения доступа к его пакетам. Используйте в домашнем каталоге команду curl для получения скрипта установки предпочитаемой версии. Замените 14.x предпочитаемым номером версии (если он отличается).

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

Просмотрите содержимое загруженного скрипта в nano (или другом предпочитаемом текстовом редакторе):

Убедившись в безопасности запуска скрипта, закройте редактор и запустите скрипт с привилегиями sudo :

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

Убедитесь в установке новой версии, запустив node с флагом версии -v :

Пакет NodeSource nodejs содержит двоичный код node и npm , так что не нужно устанавливать npm отдельно.

Вы успешно установили Node.js и npm , используя apt и архив NodeSource PPA. В следующем разделе мы покажем, как использовать диспетчер версий Node Version Manager для установки нескольких версий Node.js и управления ими.

Вариант 3 — Установка Node с помощью Node Version Manager

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

Чтобы установить NVM на ваш сервер Ubuntu 20.04, откройте страницу проекта на GitHub. Скопируйте команду curl из файла README, отображаемого на главной странице. Она позволит получить самую последнюю версию скрипта установки.

Прежде чем передавать команду в bash , рекомендуется проверить скрипт, чтобы убедиться, что он не делает ничего, с чем вы не согласны. Вы можете сделать это, удалив сегмент | bash в конце команды curl :

Проверьте и убедитесь, что вы не возражаете против изменений, которые вносит скрипт. Если вас удовлетворит результат, запустите команду еще раз с добавлением | bash в конце. URL-адрес, который вы используете, будет меняться в зависимости от последней версии NVM, но в настоящий момент скрипт можно загрузить и запустить с помощью следующей команды:

Она устанавливает скрипт nvm для вашей учетной записи. Для его использования необходимо сначала получить ваш файл .bashrc :

Теперь вы можете спросить у NVM, какие версии Node доступны:

Это очень длинный список! Вы можете установить версию Node, введя любую версию релиза, которую вы видите. Например, для получения версии 13.6.0 воспользуйтесь следующей командой:

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

Она отображает текущую активную версию на первой строке ( -> v13.6.0 ), за которой следуют псевдонимы и версии, на которые указывают эти псевдонимы.

Примечание. Если у вас также имеется версия Node.js, установленная с помощью apt , здесь вы сможете увидеть системную запись. Вы всегда можете активировать установленную системой версию Node с помощью команды nvm use system ​​​.

Также вы увидите псевдонимы для различных релизов Node с длительной поддержкой (LTS):

Мы можем установить релиз на основе этих псевдонимов. Например, для установки последней версии с долгосрочной поддержкой, erbium , запустите следующую команду:

Вы можете переключаться между установленными версиями с помощью nvm use :

Вы можете проверить, что установка выполнена успешно, с помощью того же метода, использованного в других разделах. Введите следующую команду:

Корректная версия Node установлена на нашем компьютере, как мы и ожидали. Совместимая версия npm также доступна.

Заключение

Существует несколько способов запустить и начать использование Node.js на сервере Ubuntu 20.04. Наиболее подходящий метод из вышеперечисленных определяется в зависимости от обстоятельств. Хотя использование упакованной версии из репозитория Ubuntu — самый простой метод, использование nvm или архива NodeSource PPA дает дополнительную гибкость.

Дополнительную информацию о программировании с помощью Node.js можно найти в нашей серии обучающих материалов «Программирование на Node.js».

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Установка Node.js через пакетный менеджер

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

Android

Поддержка Android все еще является экспериментальной в Node.js, поэтому предварительно скомпилированные двоичные файлы еще не предоставлены в открытом доступе.

Однако есть и сторонние решения. Например, сообщество Termux предоставляет эмулятор терминала и среду Linux для Android, а также собственный менеджер пакетов и обширную коллекцию многих предварительно скомпилированных приложений. Эта команда в приложении Termux установит последнюю доступную версию Node.js:

В настоящее время двоичные файлы Termux Node.js связаны с system-icu (в зависимости от пакета libicu ).

Arch Linux

Пакеты Node.js и npm доступны в репозитории сообщества.

Дистрибутивы Linux на основе Debian и Ubuntu, пакеты Enterprise Linux/Fedora и Snap

FreeBSD

Самый последний выпуск Node.js доступен через порт www/node.

Установите бинарный пакет через pkg:

Или скомпилируйте свой используя порты:

Gentoo

Node.js доступен в дереве портежей.

NetBSD

Node.js доступен в дереве pkgsrc:

Или установите бинарный пакет (если он доступен для вашей платформы) с помощью pkgin:

Node Version Manager ― это bash-скрипт, используемый для управления несколькими выпущенными версиями Node.js. Он позволяет выполнять такие операции, как установка, удаление, переключение версий и т.д.. Чтобы установить nvm, используйте этот скрипт установки.

В системах Unix/OS X Node.js, созданный из исходного кода, можно установить с помощью nvm путем установки в папку по умолчанию nvm:

После этого вы можете использовать nvm для переключения между выпущенными версиями и версиями построенных из исходного кода. Например, если версия Node.js v8.0.0-pre:

После выхода официального релиза вы захотите удалить встроенную версию:

Windows

The nvs version manager is cross-platform and can be used on Windows, macOS, and Unix-like systems

To install nvs on Windows go to the release page here and download the MSI installer file of the latest release.

You can also use chocolatey to install it:

macOS,UnixLike

You can find the documentation regarding the installation steps of nvs in macOS/Unix-like systems here

Usage

After this you can use nvs to switch between different versions of node.

To add the latest version of node:

Or to add the latest LTS version of node:

Then run the nvs use command to add a version of node to your PATH for the current shell:

To add it to PATH permanently, use nvs link :

OpenBSD

Node.js доступен через систему портов.

Использование pkg_add в OpenBSD:

openSUSE и SLE

Node.js доступен в основных репозиториях в следующих пакетах:

  • openSUSE Leap 42.2: nodejs4
  • openSUSE Leap 42.3: nodejs4 , nodejs6
  • openSUSE Tumbleweed: nodejs4 , nodejs6 , nodejs8
  • SUSE Linux Enterprise Server (SLES) 12: nodejs4 , nodejs6 ("Модуль Web и Scripting" должен быть добавлен перед установкой.)

Например, чтобы установить Node.js 4.x в openSUSE Leap 42.2, запустите следующее от имени пользователя root:

macOS

Просто загрузите установщик macOS прямо с веб-сайта nodejs.org.

Если вы хотите скачать пакет с bash:

Альтернативы

Использование Homebrew:

Использование MacPorts:

Использование pkgsrc:

Установка бинарных файлов:

Или сборка с помощью pkgsrc:

SmartOS и illumos

Образы SmartOS поставляются с предустановленным pkgsrc. В других дистрибутивах Illumos сначала установите pkgsrc, затем вы сможете установить бинарный пакет как обычно:

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

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