Installing multiple versions of node.js using nvm

License

nvm is released under the MIT license.

Copyright (C) 2010 Tim Caswell and Jordan Harband

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Docker For Development Environment

To make the development and testing work easier, we have a Dockerfile for development usage, which is based on Ubuntu 14.04 base image, prepared with essential and useful tools for development, to build the docker image of the environment, run the docker command at the root of repository:

$ docker build -t nvm-dev .

This will package your current nvm repository with our pre-defined development environment into a docker image named , once it’s built with success, validate your image via :

$ docker images

REPOSITORY         TAG                 IMAGE ID            CREATED             SIZE
nvm-dev            latest              9ca4c57a97d8        7 days ago          650 MB

If you got no error message, now you can easily involve in:

$ docker run -h nvm-dev -it nvm-dev

nvm@nvm-dev:~/.nvm$

Please note that it’ll take about 8 minutes to build the image and the image size would be about 650MB, so it’s not suitable for production usage.

For more information and documentation about docker, please refer to its official website:

License

nvm is released under the MIT license.

Copyright (C) 2010 Tim Caswell and Jordan Harband

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

VS Code support

Visual Studio Code can use NVS to select a node version to use when launching or debugging. In , add a attribute with an NVS version string and a attribute that refers to (Windows) or (Mac, Linux). (You may need to specify an absolute path such as if NVS is not in VS Code’s PATH.)

Example: Configure so VS Code uses NVS to launch node version 6.10:

  "configurations": ,
      "runtimeArgs": ,
      "windows": { "runtimeExecutable": "nvs.cmd" },
      "osx": { "runtimeExecutable": "nvs" },
      "linux": { "runtimeExecutable": "nvs" }
    },

Or, remove the version string from to get the version from a file in the project directory. For more details, see the NVS VS Code documentation or run .

Specifying Node Versions

There are a variety of ways of specifying the target node version for commands. Most commands use the latest matching version, and lists multiple matching versions.

Numeric version numbers can be complete or incomplete, with an optional leading .

  • : 8.x.y versions
  • : 6.1.x versions

There are labels for two especially useful versions:

  • : newest Long Term Support official release
  • , : newest official release

There is an label to read the target version from a file in the current directory, or any parent directory. looks for in order:

  • : version on single line. Custom to .
  • : version on single line. Used by multiple tools: node-version-usage
  • : version on single line. Used by .
  • : use field to determine compatible . Requires an installed version of , and uses to resolve complex ranges.

There is support for the named release streams:

argon, boron, carbon: codenames for LTS release streams

These node support aliases may be used, although simply simply resolve to the latest matching version:

active, lts_active, lts_latest, lts, current, supported

Installation

Let’s first cover installation for Windows, macOS and Linux.

Windows

First, we need to do a little preparation:

  • uninstall any existing versions of Node.js
  • delete any existing Node.js installation directories (such as )
  • delete the existing npm install location (such as )

After this, download and run the latest stable installer and you should be good to go!

macOS/Linux

Unlike Windows, removing previous Node and npm installations in macOS and Linux is optional. If this is something you want to do, there are plenty of good resources available online. For example, here’s how to remove Node on macOS and on Linux. And here’s how you can remove any previous npm installation you might have.

You can install nvm using cURL or Wget. On your terminal, run the following:

With cURL:

Or with Wget:

Note that the version number () will change as the project develops, so it’s worth checking the to find the most recent version.

This will clone the nvm repository to and will make the required changes to your bash profile, so that is available from anywhere in your terminal.

And that’s it! Reload (or restart) your terminal and nvm is ready to be used.

Installation

Nodist was designed to replace any existing node.js installation, so if node is already installed on your machine, uninstall it first.

Activating nodist in cygwin

Before you are able to use nodist in cygwin you need to run the following in your cygwin terminal after installing nodist:

Activating nodist in PowerShell

You might need to ‘Unblock’ the file by right clicking on it in the Explorer and selecting that menu entry.

If you cannot see the unblock option after right-clicking > Properties in Explorer you can also perform the unblock via the following PowerShell command:

If you still cannot run nodist you may also need amend your ExecutionPolicy setting.

Make it work in your IDE

If your IDE cannot access node or npm right away, don’t fret! Find the relevant configuration settings and either set as the Node installation dir or set as the path to the node binary directly.

Similar for npm: either set as the installation path or directly. Some IDEs (eg. WebStorm) require you to set the path to an npm package containing . Nodist comes with a proxy npm folder: Simply set as the npm package (this feature is experimental and feedback is appreciated!).

Migrating from 0.7 or lower

If you’re looking to upgrade your Nodist installation, the easiest way is to uninstall (see below) the old installation and install the new version with the installer above.
You may need to reset your per-directory node version settings in order for them to work in v0.8 (ones set using nodist v0.6 should work fine, ones set using v0.7 will not).

Important usage changes in v0.8

Starting in v0.8 Nodist employs lazy version pattern evaluation. This means that setting versions per env/locally/globally doesn’t set an explicit version, if you didn’t give one. Instead the node.exe shim chooses a suitable version at runtime. Commands for installing a version and setting a requirement have been separated, thus, to update your node version (if your global version is set to , e.g.), you now need to run (i.e. doesn’t do that for you anymore), which is probably how it should have worked all along.

Uninstall (v0.7)

  1. Run the uninstaller either from the directory where you installed nodist, or from the Software Control Panel

  2. Make sure to completely remove the nodist directory. (This will remove all your globally installed npm modules. If you don’t want that, remove everything else, other than .)

Uninstall (before v0.7)

  1. Remove the env var.

  2. Delete the nodist directory

  3. Run on the command prompt to restore NPM functionality if you are going back to the official node install.

Known issues

Please read this!

Over the past months several problems have presented themselves, which are due to the way nodist works and are hard to fix:

  • process signals: Nodist employs a wrapper executable to shim the functionality of Node. Since Windows doesn’t have signals, sending a SIGTERM, or similar will probably not be propagated to the actual node process, but get stuck in the shim. (see #173)
  • native modules: Since the node version changes at the mercy of the shim executable, based on env vars, target directory and the global setting, and availability of node versions, it is possible that locally or globally installed node modules that depend on a specific version of node (usually native modules and downloaders) stop working. makes things work again in these cases.

Docker For Development Environment

To make the development and testing work easier, we have a Dockerfile for development usage, which is based on Ubuntu 14.04 base image, prepared with essential and useful tools for development, to build the docker image of the environment, run the docker command at the root of repository:

$ docker build -t nvm-dev .

This will package your current nvm repository with our pre-defined development environment into a docker image named , once it’s built with success, validate your image via :

$ docker images

REPOSITORY         TAG                 IMAGE ID            CREATED             SIZE
nvm-dev            latest              9ca4c57a97d8        7 days ago          650 MB

If you got no error message, now you can easily involve in:

$ docker run -h nvm-dev -it nvm-dev

nvm@nvm-dev:~/.nvm$

Please note that it’ll take about 8 minutes to build the image and the image size would be about 650MB, so it’s not suitable for production usage.

For more information and documentation about docker, please refer to its official website:

Bootstrapping node

NVS uses a small amount of platform-specific shell code that bootstraps the tool by automatically downloading a private copy of node. The bootstrap code is just a few dozen lines each of Windows command script, Windows powershell script, and POSIX shell script. Besides bootstrapping, the shell scripts are also used to export PATH changes to the calling shell (which a separate node process cannot do). But all the code for querying available versions, downloading and installing node and matching npm, switching versions/architectures/engines, uninstalling, parsing and updating PATH, and more can be written in JavaScript, and mostly in a cross-platform way.

Installing Unix nvm

Because this is implemented in node.js, it happens to work on Unix also. It just need a different install script using bash.

To retrieve and run the install script, provided below are three options for you to choose from in case one of them is down.

Please pick one and then copy and paste it into a bash terminal to run.

Installing from github.com

Retrieve the install script from github.com:

Using cURL and the install script:

NVM_HOME=~/nvm curl -o- https://raw.githubusercontent.com/jchip/nvm/v1.4.2/install.sh | bash

or wget:

NVM_HOME=~/nvm wget -qO- https://raw.githubusercontent.com/jchip/nvm/v1.4.2/install.sh | bash

Installing from unpkg.com

Using cURL and the install script:

NVM_HOME=~/nvm curl -o- https://unpkg.com/@jchip/nvm@1.4.2/install.sh | bash

or wget:

NVM_HOME=~/nvm wget -qO- https://unpkg.com/@jchip/nvm@1.4.2/install.sh | bash

Installing from jsdelivr.net

Using cURL and the install script:

NVM_HOME=~/nvm curl -o- https://cdn.jsdelivr.net/npm/@jchip/nvm@1.4.2/install.sh | bash

or wget:

NVM_HOME=~/nvm wget -qO- https://cdn.jsdelivr.net/npm/@jchip/nvm@1.4.2/install.sh | bash

Usage

Nodist allows you to set version requirements for different scopes.
Version requirements can be fully specified versions, like or patterns like , , or .
io.js is supported natively: Since node and io.js versions form a continuum you can simply use io.js versions as if they were node versions.
Setting a requirement installs a matching version only if there is no other matching version already installed; otherwise existing installed versions will get referenced when executing .

Scope precedence

The following is a list of all scopes ordered by precedence (the first scope is the one with the highest priority; only if it’s not set, the second scope is examined).

  1. Environment (and env vars)
  2. (optional:) Package ( with an field in the directory of interest or one of its parent directories)
  3. Directory ( or in the directory of interest or one of its parent directories)
  4. Global (globally set node or npm version)

When you’re just running node, the directory of interest is the directory of the javascript file to be executed. When running npm, it is the current working directory.

Package.json inspection is turned off by default as of nodist v0.8.5. You can turn it on by setting .

npm

Any instances of node invoked by npm will be locked to the same version npm runs on.

Currently, all node and npm versions share the same global npm module space.

If you have installed native modules (globally or locally) you may have to run after changing the node version (implicitly or explicitly). There is an open issue about how to avoid rebuilding globally installed native modules, feedback/input is welcome.

macOS Troubleshooting

nvm node version not found in vim shell

If you set node version to a version other than your system node version and open vim and run you should see if you see your system version . You need to run:

sudo chmod ugo-x /usr/libexec/path_helper

More on this issue in .

nvm is not compatible with the npm config «prefix» option

Some solutions for this issue can be found here

There is one more edge case causing this issue, and that’s a mismatch between the path and the user’s home directory’s actual name.

You have to make sure that the user directory name in and the user directory name you’d see from running are capitalized the same way (See this issue).

Installing nvm on Alpine Linux

In order to provide the best performance (and other optimisations), nvm will download and install pre-compiled binaries for Node (and npm) when you run . The Node project compiles, tests and hosts/provides these pre-compiled binaries which are built for mainstream/traditional Linux distributions (such as Debian, Ubuntu, CentOS, RedHat et al).

There is a flag for which requests nvm download Node source and compile it locally.

If installing nvm on Alpine Linux is still what you want or need to do, you should be able to achieve this by running the following from you Alpine Linux shell:

apk add -U curl bash ca-certificates openssl ncurses coreutils python2 make gcc g++ libgcc linux-headers grep util-linux binutils findutils
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

The Node project has some desire but no concrete plans (due to the overheads of building, testing and support) to offer Alpine-compatible binaries.

As a potential alternative, @mhart (a Node contributor) has some Docker images for Alpine Linux with Node and optionally, npm, pre-installed.

Installing nvm on Alpine Linux

In order to provide the best performance (and other optimisations), nvm will download and install pre-compiled binaries for Node (and npm) when you run . The Node project compiles, tests and hosts/provides these pre-compiled binaries which are built for mainstream/traditional Linux distributions (such as Debian, Ubuntu, CentOS, RedHat et al).

There is a flag for which requests nvm download Node source and compile it locally.

If installing nvm on Alpine Linux is still what you want or need to do, you should be able to achieve this by running the following from you Alpine Linux shell:

apk add -U curl bash ca-certificates openssl ncurses coreutils python2 make gcc g++ libgcc linux-headers grep util-linux binutils findutils
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

The Node project has some desire but no concrete plans (due to the overheads of building, testing and support) to offer Alpine-compatible binaries.

As a potential alternative, @mhart (a Node contributor) has some Docker images for Alpine Linux with Node and optionally, npm, pre-installed.

macOS Troubleshooting

nvm node version not found in vim shell

If you set node version to a version other than your system node version and open vim and run you should see if you see your system version . You need to run:

sudo chmod ugo-x /usr/libexec/path_helper

More on this issue in .

nvm is not compatible with the npm config «prefix» option

Some solutions for this issue can be found here

There is one more edge case causing this issue, and that’s a mismatch between the path and the user’s home directory’s actual name.

You have to make sure that the user directory name in and the user directory name you’d see from running are capitalized the same way (See this issue).

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

Теперь, когда у вас установлен nvm, пришло время добавить новую версию Node.js. Для этого потребуется прочитать справку, которую можно вызвать, используя команду
.

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

Обратите внимание, что здесь не хватает 5-ой версии Node.js. Дело в том, что создатель nvm для Windows ещё не подготовил новый релиз, добавляющий 5-ую версию Node.js в этот список

Итак, установим последнюю версию Node.js четвертой ветки. Для этого, к сожалению, потребуется полностью прописать версию Node.js, хотя в версии под Linux и OSX можно просто указывать мажорную цифру (4 или 5).

Тоже самое можно проделать с пятой веткой:

Помимо версии, при установке есть возможность указать разрядность, например, для установки Node.js 5.1.0 32-битной разрядности следует выполнить

Commands

List Node.js (and io.js) versions available
(fetches their lists from respective sites).
will list all 4.*.* versions available.

install

Install latest of specified Node.js versions.
One can select platform ( or )
or default will be used.

If specified version is installed,
it will be ,
so it is safe to run
to ensure the latest version in installed.

To force reinstallation, add
to the end of command,
eg will reinstall
latest version unconditionally.

use

Switch to latest of installed versions
(filters apply).
Eg means switch to latest of all,
while to latest of iojs.

Run to temporarily make node.exe
unavailable,
you can switch back at any moment later.

remove

Remove oldest of installed versions
considering command line filter.

For security reasons,
must occur at the end of
this command,
or else it will refuse to proceed.

Eg, ( is alias for )
will remove one (minimal) version.
will remove all iojs versions.

Actual removing of files
can take much time,
so it is performed in background.
Don’t logoff or turn off your computer
a minute or two after this command finished.

openssl

Node.js versions 0.*.* contains binary.
can download it and install
into its PATH.

Like command,
platform can be specified.
Other filters (version number for instance)
are meaningless hence ignored.

abbrev

Helps to find comman abbreviation(s).
Eg, run to see all commands,
starting with and their alternatives.

Plain shows all abbreviations.

upgrade

Upgrades itself and/or Node.js
(current or LTS).

Self upgrade is .

For upgrading Node.js specify or
and (optionally) platform
( or ).
These arguments will be
passed to regular
command.

bye

Fully uninstall itself along with
all Node.js versions.

Like command,
requires to proceed
and take some (more) time
for actual files removal
(may be 10 minutes or so).

Command reference

Command Description
Get detailed help for a command
Initialize your profile for using NVS
Remove NVS from profile and environment
Display the NVS tool version
Download and extract a node version
Remove a node version
Migrate global modules
Upgrade to latest patch of major version
Use a node version in the current shell
Automatically switch based on cwd
Run a script using a node version
Run an executable using a node version
Show the path to a node version binary
List local node versions
List node versions available to download
Link a version as the default
Remove links to a default version
Set or recall aliases for versions
Set or recall download base URIs

A version or filter consists of a complete or partial semantic version number or version label («lts», «latest», «Argon», etc.), optionally preceded by a remote name, optionally followed by an architecture, separated by slashes. Examples: «lts», «4.6.0», «6/x86», «node/6.7/x64».

Refer to the docs for more details about each command.

Installation

Since you probably already have , the easiest way to install is through :

Once installed, caches versions in subdirectory of the directory specified in environment variable , which defaults to ; and the active version is installed directly in .

To avoid requiring for and global installs, it is suggested you either install to your home directory using , or take ownership of the system directories:

If is not yet available, one way to bootstrap an install:

Alternatively, you can clone this repo and

to install to of the directory specified in the environment variable , which defaults to (note that you will likely need to use ). To install in a custom location (such as ), run .

Third Party Installers

On Linux and macOS, n-install allows installation directly from GitHub; for instance:

n-install sets both and to , installs to , modifies the initialization files of supported shells to export and add to the , and installs the latest LTS version.

As a result, both itself and all versions it manages are hosted inside a single, optionally configurable directory, which you can later remove with the included script. updates itself to the latest version. See the n-install repo for more details.

Related

  • Tutorial

    Django — это мощная веб-система, помогающая создать приложение или сайт Python с нуля. Django включает упрощенный сервер разработки для локального тестирования кода, однако для серьезных производственных задач требуется более защищенный и мощный веб-сервер. В этом руководстве…

  • Tutorial

    Автор выбрал фонд Electronic Frontier Foundation для получения пожертвований в рамках программы Write for DOnations. Cloudflare — это…

  • Tutorial

    Автор выбрал фонд Electronic Frontier Foundation для получения пожертвований в рамках программы Write for DOnations. Cloudflare — это…

  • Tutorial
    Настройка приложения Node.js для работы в среде Ubuntu 20.04

    Node.js — среда исполнения JavaScript с открытым исходным кодом, предназначенная для построения серверных и сетевых приложений. Данная платформа работает в операционных системах Linux, macOS, FreeBSD и Windows. Хотя вы можете запускать приложения Node.js…

System linking

If is under a system path such as or , then the command additionally links into well-known Node.js system locations. (This is only allowed if there is not already a system-installed node.)

  • On non-Windows platforms, symbolic links are created in for , , and any globally-installed node modules that have executables. Note after installing or uninstalling global modules that include executables it may be necessary to run again to update the global links. Using NVS to link a different version of node (with different global modules) updates all the links accordingly.

  • On Windows, a symbolic directory link is created at , and that directory is added to the system .

This system linking functionality is skipped when points to a non-system directory, because it would be wrong to create symlinks in system directories to user files.

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

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