Установка node.js в ubuntu при помощи nvm

Node Packaged Modules

Managing packages with npm

Installing packages

Any package can be installed using:

$ npm install packageName

This command installs the package in the current directory under and executables under .

For a system-wide installation global switch can be used:

# npm -g install packageName

By default this command installs the package under and requires root privileges to do so.

Allow user-wide installations
~/.profile
PATH="$HOME/.node_modules/bin:$PATH"
export npm_config_prefix=~/.node_modules

Re-login or source to update changes.

You can also specify the parameter for . However, this is not recommended, since you’ll need to add it every time you install a global package.

$ npm -g install packageName --prefix ~/.node_modules

Updating packages

Updating packages is as simple as

$ npm update packageName

For the case of globally installed packages ()

# npm update -g packageName

Note: Remember that globally installed packages require administrator privileges unless is set to a user-writable directory

Updating all packages

However, sometimes you may just wish to update all packages, either locally or globally. Leaving off the packageName will attempt to update all packages

$ npm update

or add the flag to update globally installed packages

# npm update -g

Removing packages

To remove a package installed with the switch simply use:

# npm -g uninstall packageName

Note: Remember that globally installed packages require administrator privileges

to remove a local package drop the switch and run:

$ npm uninstall packageName

Listing packages

To show a tree view of the installed globally packages use:

$ npm -g list

This tree is often quite deep. To only display the top level packages use:

$ npm list --depth=0

To display obsolete packages that may need to be updated:

$ npm outdated

Some node.js packages can be found in Arch User Repository with the name .

Troubleshooting

node-gyp python errors

This article or section is out of date.

Some node modules use the utility which does not support Python 3, which in most cases will be the default system-wide Python executable. To resolve such errors, make sure you have installed, then set the default npm Python like so:

$ npm config set python /usr/bin/python2

In case of errors like , option might help:

# npm install --unsafe-perm -g node-inspector

Cannot find module … errors

Since npm 5.x.x. package-lock.json file is generated along with the package.json file. Conflictions may arise when the two files refer to different package versions. A temporary method to solving this problem has been:

$ rm package-lock.json
$ npm install

Instalación de la versión Distro-Stable para Ubuntu

Ubuntu 18.04 contiene una versión de Node.js en sus repositorios predeterminados que puede utilizarse para proporcionar una experiencia uniforme en varios sistemas. En el momento en que se redactó este artículo, la versión de los repositorios fue la 8.10.0. Esta no será la versión más reciente, pero debería ser estable y bastar para una rápida experimentación con el lenguaje.

Para obtener esta versión, puede utilizar el administrador de paquetes . Actualice su índice de paquetes locales escribiendo lo siguiente:

Instale Node.js desde los repositorios:

Si el paquete de los repositorios se ajusta a sus necesidades, será todo lo que necesita para configurar Node.js. En la mayoría de los casos, también le convendrá instalar , el administrador de paquetes de Node.js. Puede hacerlo escribiendo lo siguiente:

Esto le permitirá instalar módulos y paquetes para utilizarlos con Node.js.

Debido a un conflicto con otro paquete, el ejecutable de los repositorios de Ubuntu se llama en vez de . Téngalo en cuenta al ejecutar el software.

Para comprobar la versión de Node.js que instaló después de estos pasos iniciales, escriba lo siguiente:

Cuando determine la versión de Node.js que instaló desde los repositorios de Ubuntu, podrá decidir si desea trabajar con diferentes versiones, archivos de paquetes o administradores de versiones. A continuación, veremos estos elementos junto con métodos de instalación más flexibles y sólidos.

Removing Node.js

You can uninstall Node.js using or nvm, depending on the version you want to target. To remove the distro-stable version, you will need to work with the utility at the system level.

To remove the distro-stable version, type the following:

This command will remove the package and retain the configuration files. These may be of use to you if you intend to install the package again at a later point. If you don’t want to save the configuration files for later use, however, then run the following:

This will 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:

To uninstall a version of Node.js that you have enabled using nvm, first determine whether or not the version you would like to remove is the current active version:

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 deactive nvm to enable your changes:

You can now uninstall the current version using the uninstall command above, which will remove all files associated with the targeted version of Node.js except the cached files that can be used for reinstallment.

Установка стабильной версии дистрибутива для Debian

Версия Node.js содержится в хранилищах Debian по умолчанию. На момент составления этого обучающего модуля это версия 4.8.2, срок использования которой заканчивается в конце апреля 2018 года. Если вы хотите поэкспериментировать с языком программирования, используя стабильную и достаточную версию, имеет смысл установить версию из хранилища. Однако для целей разработки и использования в работе рекомендуется установить более позднюю версию с PPA. На следующем шаге мы расскажем, как выполнить установку с PPA.

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

Затем следует установить пакет Node.js из хранилища:

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

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

В свзяи с конфликтом с другим пакетом исполняемый файл из хранилищ Debian носит имя , а не . Это необходимо помнить при запуске программного обеспечения.

Определив номер версии Node.js, установленной из хранилищ Debian, вы можете решить, хотите ли вы работать с разными версиями, архивами пакетов или диспетчерами версий. Затем мы обсудим эти элементы, а также более гибкие и надежные методы установки.

Installation mit NVM

Eine Alternative zur Installation von Node.js mit ist ein Tool namens , das für „Node.js Version Manager“ steht. läuft auf der Ebene eines unabhängigen Verzeichnisses in Ihrem Stammverzeichnis anstatt auf Betriebssystemebene. Das bedeutet, dass Sie ohne Auswirkungen auf das gesamte System mehrere in sich geschlossene Versionen von Node.js installieren können.

Durch die Kontrolle Ihrer Umgebung mit können Sie auf die neuesten Versionen von Node.js zugreifen und frühere Versionen beibehalten und verwalten. Es ist jedoch ein anderes Utility als und die Versionen von Node.js, die Sie damit verwalten, unterscheiden sich von den Versionen, die Sie mit verwalten.

Um das Installationsskript von der GitHub-Seite des Projekts herunterzuladen, können Sie verwenden. Beachten Sie, dass sich die Versionsnummer von der hier hervorgehobenen eventuell unterscheidet:

Untersuchen Sie das Installationsskript mit :

Führen Sie das Skript mit aus:

Damit wird die Software in ein Unterverzeichnis Ihres Stammverzeichnisses unter installiert. Es werden auch die zur Verwendung erforderlichen Zeilen in Ihre Datei eingefügt.

Um auf die Funktionalität Zugriff zu erhalten, müssen Sie sich entweder ab- und wieder anmelden oder sich auf die Datei beziehen, damit Ihre aktuelle Sitzung über die Änderungen informiert wird:

Wenn installiert ist, können Sie isolierte Node.js Versionen installieren. Für Informationen zu den verfügbaren Versionen von Node.js geben Sie Folgendes ein:

Wie Sie sehen können, ist die aktuelle LTS-Version zum Zeitpunkt der Abfassung v8.11.1. Sie können die Installation vornehmen, indem Sie Folgendes eingeben:

wechselt normalerweise auf die neueste installierte Version. Sie können mitteilen, die Version zu verwenden,die sie gerade heruntergeladen haben, indem Sie Folgendes eingeben:

Wenn Sie Node.js mit installieren, wird die ausführbare Datei genannt. Sie können die von der Shell derzeit verwendete Version sehen, indem Sie Folgendes eingeben:

Wenn Sie mehrere Node.js Versionen haben, können Sie prüfen, welche installiert ist, indem Sie Folgendes eingeben:

Wenn Sie eine der Versionen als Standard festlegen möchten, geben Sie Folgendes ein:

Diese Version wird automatisch für eine neue Sitzung ausgewählt. Sie können sich auch, wie folgt, über den Alias darauf verweisen:

Jede Version von Node.js verfolgt ihre eigenen Pakete und kann diese über verwalten.

Sie können auch anweisen, Pakete im Verzeichnis des Node.js Projekts zu installieren. Verwenden Sie die folgende Syntax, um das -Modul zu installieren:

Wenn Sie das Modul global installieren und es anderen Projekten mit der gleichen Version von Node.js bereitstellen möchten, können Sie die Flag hinzufügen.

Damit wird das Paket installiert in:

Wenn Sie das Modul global installieren, können Sie Befehle aus der Befehlszeile ausführen, aber Sie müssen das Paket mit Ihrem lokalen Umfeld verbinden, damit ein Programm es aufrufen kann:

Erfahren Sie mehr über die mit zur Verfügung stehenden Optionen, indem Sie Folgendes eingeben:

Настройка

Как только я наконец установил Node.js, я столкнулся с проблемами, связанными с NPM установленными глобально. Решение заключалось в том, чтобы добавить некоторые строки к переменным окружения.

Шаг 5: Проверьте NPM глобально

По умолчанию для глобальных пакетов используется home/yourusername/local/bin. Вы сможете увидеть, где установлены ваши глобальные пакеты. Чтобы проверить, нужно  вписать в bash:

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

Шаг 6: Добавить в Bash Startup

Чтобы исправить это, добавьте следующую строку в файл .bashrc, который находится в вашем домашнем каталоге (не забудьте изменить его, если ваш глобальный каталог пакетов отличается):

Installation unter Verwendung eines PPA

Um eine neuere Version von Node.js zu erhalten, können Sie das PPA (persönliches Paketarchiv) hinzufügen, das von NodeSource gepflegt wird. Diese enthalten aktuellere Versionen von Node.js als die offiziellen Ubuntu Repositorys, und Sie haben die Wahl zwischen Node.js v6.x (Support bis April 2019), Node.js v8.x (die aktuelle LTS-Version, Support bis Dezember 2019), Node.js v10.x (die zweite aktuelle LTS-Version, Support bis April 2021) und Node.js v11.x (die aktuelle Version, Support bis Juni 2019).

Installieren Sie zunächst das PPA, um Zugriff auf dessen Inhalt zu erhalten. Verwenden Sie aus dem Stammverzeichnis, um das Installationsskript für Ihre bevorzugte Version abzurufen, und achten Sie darauf, durch Ihre bevorzugte Versionszeichenfolge zu ersetzen (sofern sich diese unterscheiden):

Sie können den Inhalt dieses Skripts mit (oder Ihrem bevorzugten Texteditor) prüfen:

Führen Sie das Skript unter aus:

Das PPA wird Ihrer Konfiguration hinzugefügt und Ihr lokaler Paket-Cache automatisch aktualisiert. Nach der Durchführung des Setup-Skripts aus Nodesource können Sie das Node.js Paket auf die gleiche Art installieren, wie Sie es oben getan haben:

Um zu prüfen, welche Version von Node.js Sie nach diesen ersten Schritten installiert haben, geben Sie Folgendes ein:

Das Paket enthält das binäre sowie , daher müssen Sie nicht separat installieren.

verwendet eine Konfigurationsdatei in Ihrem Home Verzeichnis, um Aktualisierungen zu verfolgen. Sie wird erstellt, wenn Sie das erste Mal ausführen. Führen Sie diesen Befehl aus, um zu verifizieren, dass installiert ist, und um die Konfigurationsdatei zu erstellen:

Damit bestimmte Pakete funktionieren (z. B. jene, deren Code aus Source erstellt werden muss), müssen Sie das Paket installieren:

Jetzt haben Sie die notwendigen Tools, um mit Paketen zu arbeiten, deren Code aus Source erstellt werden muss.

Установка NVM

NVM (Node.js version manager) — менеджер версий Node.js.

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

Для того, чтобы у нас была возможность собирать пакеты из исходников нам необходимо установить build-essential. По традиции, для начала обновимся. И так, открываем терминал:

sudo apt-get update

А теперь устанавливаем пакеты из репозитория, которые позволят нам собирать пакеты из исходников, для этого выполняем команду:

sudo apt-get install build-essential libssl-dev

Далее загружаем установочный скрипт nvm с github https://github.com/creationix/nvm, для этого выполняем команду:

curl https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | sh

Где v0.32.0 — текущая версия скрипта, ее можно узнать в репозитори на github.

Команда загрузит и запустит скрипт. Все будет установлено в домашнюю директорию текущего пользователя в папку ~/.nvm. Также будут добавлены изменения в файл ~/.profile которые нужны для работы и настройки.

Для работы с nvm нужно перелогиниться или использовать следующую команду, чтобы не прерывать текущую сесию:

source ~/.profile

Node.js entfernen

Je nach anvisierter Version können Sie Node.js mit oder deinstallieren. Um die distro-stabile Version zu entfernen, müssen Sie mit dem -Utility auf Systemebene arbeiten.

Um die distro-stabile Version zu entfernen, geben Sie Folgendes ein:

Mit diesem Befehl entfernen Sie das Paket und behalten die Konfigurationsdateien bei. Das kann nützlich sein, wenn Sie das Paket später erneut installieren wollen. Wenn Sie die Konfigurationsdateien nicht zur späteren Verwendung speichern möchten, führen Sie Folgendes aus:

Damit wird das Paket deinstalliert und die damit verbundenen Konfigurationsdateien werden entfernt.

Als letzten Schritt können Sie alle ungenutzten Pakete entfernen, die automatisch mit dem entfernten Paket installiert wurden:

Um eine Version von Node.js, die Sie mit aktiviert haben, zu deinstallieren, bestimmen Sie zunächst, ob die Version, die Sie entfernen möchten, die aktuelle, aktive Version ist:

Wenn die von Ihnen gewünschte Version nicht die aktuelle, aktive Version ist, können Sie Folgendes ausführen:

Mit diesem Befehl wird die ausgewählte Version von Node.js deinstalliert.

Wenn die Version, die Sie entfernen möchten, die aktuelle, aktive Version** ist**, müssen Sie zunächst deaktivieren, um Ihre Änderungen zu aktivieren:

Sie können jetzt die aktuelle Version mit dem Befehl wie oben deinstallieren, wodurch alle Dateien, die mit der gewünschten Version von Node.js assoziiert sind, entfernt werden, mit Ausnahme der Cache-Dateien, die zur Neuinstallierung verwendet werden können.

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.

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

Then install Node.js:

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

If the package in the repositories suits your needs, this is all you need to do to get set up with Node.js. In most cases, you’ll also want to also install , the Node.js package manager. You can do this by installing the package with :

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

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

How To Install Using a PPA

An alternative that can get you a more recent version of Node.js is to add a PPA (personal package archive) maintained by NodeSource. This will have more up-to-date versions of Node.js than the official Ubuntu repositories, and allows you to choose between Node.js v4.x (the older long-term support version, which will be supported until April of 2018), Node.js v6.x (supported until April of 2019), and Node.js v8.x (the current LTS version, supported until December of 2019).

First, you need to install the PPA in order to get access to its contents. Make sure you’re in your home directory, and use to retrieve the installation script for your preferred version, making sure to replace with your preferred version string (if different):

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

And run the script under :

The PPA will be added to your configuration and your local package cache will be updated automatically. After running the setup script from nodesource, you can install the Node.js package in the same way you did above:

To check which version of Node.js you have installed after these initial steps, type:

The package contains the binary as well as , so you don’t need to install separately.

uses a configuration file in your home directory to keep track of updates. It will be created the first time you run . Execute this command to verify that is installed and to create the configuration file:

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

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

Eliminación de Node.js

Puede desinstalar Node.js utilizando o según la versión a la que desee orientarse. Para eliminar la versión distro-stable, deberá utilizar la herramienta en el nivel del sistema.

Para eliminar la versión distro-stable, escriba lo siguiente:

Con este comando se eliminarán el paquete y los archivos de configuración. Estos pueden resultar útiles si piensa volver a instalar el paquete en el futuro. Si no quiere guardar los archivos de configuración para su uso posterior, ejecute lo siguiente:

Con esto se desinstalará el paquete y se eliminarán los archivos de configuración asociados a él.

Como paso final, puede eliminar cualquier paquete no utilizado que se haya instalado de forma automática con el paquete eliminado:

Para desinstalar una versión de Node.js que haya habilitado utilizando , primero determine si la versión que desea eliminar es o no la que se encuentra activa:

Si esto no sucede, puede ejecutar lo siguiente:

Con este comando se desinstalará la versión seleccionada de Node.js.

Si la versión que desea eliminar es la versión activa actual, primero debe desactivar para habilitar sus cambios:

Ahora podrá desinstalar la versión actual con el comando anterior, que eliminará todos los archivos asociados con la versión deseada de Node.js, a excepción de aquellos en caché que se puedan utilizar para la reinstalación.

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

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

Adblock
detector