Практическое руководство по NVM

Node.js 20 был выпущен 18 апреля 2023 года. Он поставляется с npm 9 и множеством новых функций. Готовы попробовать?

Как мы говорили в предыдущей статье, NVM (Node Version Manager) — лучший способ обновить версии node.js и npm. Это может помочь нам снизить риск.

Это переписывание с новыми версиями nvm, node.js и npm.

Установить энергонезависимую память

nvm управляет версиями node.js и npm. Он предназначен для установки для каждого пользователя и вызова для каждой оболочки. nvm работает в любой POSIX-совместимой оболочке (sh, dash, ksh, zsh, bash), особенно в Unix, macOS и Windows WSL.

Последней версией nvm является 0.39.3, и ее можно установить командой curl или wget:

% curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
% wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

В файле профиля, например ~/.zshrc, мы видим добавленные выше строки.

Использовать энергонезависимую память

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

% nvm install node
Downloading and installing node v20.0.0...
Downloading https://nodejs.org/dist/v20.0.0/node-v20.0.0-darwin-x64.tar.xz...
################################################################################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v20.0.0 (npm v9.6.4)

В приведенном выше выводе указано, что npm 9.6.4 используется вместе с node.js 20.0.0. Это можно проверить следующим образом:

% node -v
v20.0.0
% npm -v
9.6.4

Мы также можем указать точную версию для установки. Семантический формат версии определяется SemVer:

%  nvm install 16.20.0
Downloading and installing node v16.20.0...
Downloading https://nodejs.org/dist/v16.20.0/node-v16.20.0-darwin-x64.tar.xz...
################################################################################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v16.20.0 (npm v8.19.4)

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

%  nvm install 16.20.0
v16.20.0 is already installed.
Now using node v16.20.0 (npm v8.19.4)

Хотите изменить npm на версию 9.0.0?

% npm install -g [email protected]

removed 7 packages, changed 73 packages, and audited 227 packages in 2s

14 packages are looking for funding
  run `npm fund` for details

1 high severity vulnerability

To address all issues, run:
  npm audit fix

Run `npm audit` for details.

Мы можем перечислить все установленные версии:

% nvm ls
       v10.14.0
       v12.22.7
       v14.17.6
       v14.20.1
        v16.0.0
       v16.19.0
       v16.19.1
->     v16.20.0
        v17.0.0
        v17.1.0
        v17.3.0
        v18.0.0
        v19.0.0
        v20.0.0
         system
default -> 16 (-> v16.20.0)
iojs -> N/A (default)
unstable -> N/A (default)
node -> stable (-> v20.0.0) (default)
stable -> 20.0 (-> v20.0.0) (default)
lts/* -> lts/hydrogen (-> N/A)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.24.1 (-> N/A)
lts/erbium -> v12.22.12 (-> N/A)
lts/fermium -> v14.21.3 (-> N/A)
lts/gallium -> v16.20.0
lts/hydrogen -> v18.16.0 (-> N/A)
  • Стрелка в приведенном выше выводе показывает, что текущая версия node.js — 16.20.0.
  • default устанавливается на 16.20.0.
  • io.js, форк node.js, не установлен.
  • node устанавливается на 20.0.0.
  • stable устанавливается на 20.0.0.

nvm use изменяет текущую версию:

% nvm use 12.22.7
Now using node v12.22.7 (npm v8.19.2)
% nvm use 14
Now using node v14.20.1 (npm v9.0.1)
% nvm use 17.1
Now using node v17.1.0 (npm v8.1.2)
% nvm use 19.0.0
Now using node v19.0.0 (npm v9.0.1)
% nvm use 20.0.0
Now using node v20.0.0 (npm v9.6.4)
% nvm use default
Now using node v16.20.0 (npm v9.0.0)
% nvm use node
Now using node v20.0.0 (npm v9.6.4)
% nvm use stable
Now using node v20.0.0 (npm v9.6.4)
% nvm use iojs
N/A: version "iojs" is not yet installed.

You need to run `nvm install iojs` to install and use it.

Вы можете задаться вопросом, как v14.20.1 использует более позднюю версию npm (v9.0.1), чем npm v17.1.0 (v8.1.2). Этого можно добиться следующими командами:

% nvm use 14.20.1
% npm install -g [email protected]

Как мы знаем, npm 9 прекратил поддержку node.js 12. Версия 12.22.7 не может установить npm 9.0.1.

% nvm use 12.22.7
Now using node v12.22.7 (npm v8.19.2)
% npm install -g [email protected]
npm ERR! code EBADENGINE
npm ERR! engine Unsupported engine
npm ERR! engine Not compatible with your version of node/npm: [email protected]
npm ERR! notsup Not compatible with your version of node/npm: [email protected]
npm ERR! notsup Required: {"node":"^14.17.0 || ^16.13.0 || >=18.0.0"}
npm ERR! notsup Actual:   {"npm":"8.19.2","node":"v12.22.7"}

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/jenniferfu/.npm/_logs/2023-04-19T04_51.nvmrc009Z-debug-0.log

Следующая команда получит последнюю поддерживаемую версию npm для текущей версии узла:

% nvm install-latest-npm
Attempting to upgrade to the latest working version of npm...
* Installing latest `npm`; if this does not work on your node version, please report a bug!

removed 9 packages, changed 79 packages, and audited 238 packages in 2s

18 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
* npm upgraded to: v9.6.4

Для node.js 20.0.0 последней рабочей версией npm является 9.6.4.

nvm use устанавливает конкретную версию текущей оболочки. Вновь установленная версия node.js будет потеряна, если вы запустите новую оболочку.

Как мы можем сделать конкретную версию узла постоянной?

Версия по умолчанию — это версия, которая распространяется на все оболочки. nvm alias можно установить версию по умолчанию.

%  nvm alias default 16
default -> 16 (-> v16.20.0)

Для удобства можно создать файл .nvmrc, который принимает формат SemVer, либо node, либо default. После этого nvm use, nvm install, nvm exec, nvm run и nvm which будут использовать версию, указанную в файле .nvmrc, если версия не указана в командной строке.

% cat .nvmrc
20.0.0
% nvm use
Found '/Users/jenniferfu/.nvmrc' with version <20.0.0>
Now using node v20.0.0 (npm v9.6.4)

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

% nvm current
v20.0.0

ls-remote перечислены все доступные версии, но будьте готовы к очень длинному списку.

% nvm ls-remote

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

% nvm ls-remote 20
->      v20.0.0
% nvm ls-remote 19
        v19.0.0
        v19.0.1
        v19.1.0
        v19.2.0
        v19.3.0
        v19.4.0
        v19.5.0
        v19.6.0
        v19.6.1
        v19.7.0
        v19.8.0
        v19.8.1
        v19.9.0

nvm which показывает путь к исполняемому файлу, куда он был установлен. Мы установили node.js 12.22.7, 14.17.6, 16.19.1, 17.3.0, 18.0.0, 19.0.0 и 20.0.0. Вот nvm which результаты:

% nvm which 12.22.7
/Users/jenniferfu/.nvm/versions/node/v12.22.7/bin/node
% nvm which 14.17.6
/Users/jenniferfu/.nvm/versions/node/v14.17.6/bin/node
% nvm which 16.19.1
/Users/jenniferfu/.nvm/versions/node/v16.19.1/bin/node
% nvm which 17.3.0
/Users/jenniferfu/.nvm/versions/node/v17.3.0/bin/node
% nvm which 18.0.0
/Users/jenniferfu/.nvm/versions/node/v18.0.0/bin/node
% nvm which 19.0.0
/Users/jenniferfu/.nvm/versions/node/v19.0.0/bin/node
% nvm which 20.0.0
/Users/jenniferfu/.nvm/versions/node/v20.0.0/bin/node

Определенную версию узла можно использовать непосредственно для запуска приложения:

% nvm run 18.0.0 app.js

В качестве альтернативы следующая команда запускает node app.js с PATH, указывающим на узел 18.0.0.

% nvm exec 18.0.0 node app.js

Если вы хотите найти еще nvm команд, запустите команду справки:

% nvm --help

Node Version Manager (v0.39.3)

Note: <version> refers to any version-like string nvm understands. This includes:
  - full or partial version numbers, starting with an optional "v" (0.10, v0.1.2, v1)
  - default (built-in) aliases: node, stable, unstable, iojs, system
  - custom aliases you define with `nvm alias foo`

 Any options that produce colorized output should respect the `--no-colors` option.

Usage:
  nvm --help                                  Show this message
    --no-colors                               Suppress colored output
  nvm --version                               Print out the installed version of nvm
  nvm install [<version>]                     Download and install a <version>. Uses .nvmrc if available and version is omitted.
   The following optional arguments, if provided, must appear directly after `nvm install`:
    -s                                        Skip binary download, install from source only.
    -b                                        Skip source download, install from binary only.
    --reinstall-packages-from=<version>       When installing, reinstall packages installed in <node|iojs|node version number>
    --lts                                     When installing, only select from LTS (long-term support) versions
    --lts=<LTS name>                          When installing, only select from versions for a specific LTS line
    --skip-default-packages                   When installing, skip the default-packages file if it exists
    --latest-npm                              After installing, attempt to upgrade to the latest working npm on the given node version
    --no-progress                             Disable the progress bar on any downloads
    --alias=<name>                            After installing, set the alias specified to the version specified. (same as: nvm alias <name> <version>)
    --default                                 After installing, set default alias to the version specified. (same as: nvm alias default <version>)
  nvm uninstall <version>                     Uninstall a version
  nvm uninstall --lts                         Uninstall using automatic LTS (long-term support) alias `lts/*`, if available.
  nvm uninstall --lts=<LTS name>              Uninstall using automatic alias for provided LTS line, if available.
  nvm use [<version>]                         Modify PATH to use <version>. Uses .nvmrc if available and version is omitted.
   The following optional arguments, if provided, must appear directly after `nvm use`:
    --silent                                  Silences stdout/stderr output
    --lts                                     Uses automatic LTS (long-term support) alias `lts/*`, if available.
    --lts=<LTS name>                          Uses automatic alias for provided LTS line, if available.
  nvm exec [<version>] [<command>]            Run <command> on <version>. Uses .nvmrc if available and version is omitted.
   The following optional arguments, if provided, must appear directly after `nvm exec`:
    --silent                                  Silences stdout/stderr output
    --lts                                     Uses automatic LTS (long-term support) alias `lts/*`, if available.
    --lts=<LTS name>                          Uses automatic alias for provided LTS line, if available.
  nvm run [<version>] [<args>]                Run `node` on <version> with <args> as arguments. Uses .nvmrc if available and version is omitted.
   The following optional arguments, if provided, must appear directly after `nvm run`:
    --silent                                  Silences stdout/stderr output
    --lts                                     Uses automatic LTS (long-term support) alias `lts/*`, if available.
    --lts=<LTS name>                          Uses automatic alias for provided LTS line, if available.
  nvm current                                 Display currently activated version of Node
  nvm ls [<version>]                          List installed versions, matching a given <version> if provided
    --no-colors                               Suppress colored output
    --no-alias                                Suppress `nvm alias` output
  nvm ls-remote [<version>]                   List remote versions available for install, matching a given <version> if provided
    --lts                                     When listing, only show LTS (long-term support) versions
    --lts=<LTS name>                          When listing, only show versions for a specific LTS line
    --no-colors                               Suppress colored output
  nvm version <version>                       Resolve the given description to a single local version
  nvm version-remote <version>                Resolve the given description to a single remote version
    --lts                                     When listing, only select from LTS (long-term support) versions
    --lts=<LTS name>                          When listing, only select from versions for a specific LTS line
  nvm deactivate                              Undo effects of `nvm` on current shell
    --silent                                  Silences stdout/stderr output
  nvm alias [<pattern>]                       Show all aliases beginning with <pattern>
    --no-colors                               Suppress colored output
  nvm alias <name> <version>                  Set an alias named <name> pointing to <version>
  nvm unalias <name>                          Deletes the alias named <name>
  nvm install-latest-npm                      Attempt to upgrade to the latest working `npm` on the current node version
  nvm reinstall-packages <version>            Reinstall global `npm` packages contained in <version> to current version
  nvm unload                                  Unload `nvm` from shell
  nvm which [current | <version>]             Display path to installed node version. Uses .nvmrc if available and version is omitted.
    --silent                                  Silences stdout/stderr output when a version is omitted
  nvm cache dir                               Display path to the cache directory for nvm
  nvm cache clear                             Empty cache directory for nvm
  nvm set-colors [<color codes>]              Set five text colors using format "yMeBg". Available when supported.
                                               Initial colors are:
                                                  bygre
                                               Color codes:
                                                r/R = red / bold red
                                                g/G = green / bold green
                                                b/B = blue / bold blue
                                                c/C = cyan / bold cyan
                                                m/M = magenta / bold magenta
                                                y/Y = yellow / bold yellow
                                                k/K = black / bold black
                                                e/W = light grey / white
Example:
  nvm install 8.0.0                     Install a specific version number
  nvm use 8.0                           Use the latest available 8.0.x release
  nvm run 6.10.3 app.js                 Run app.js using node 6.10.3
  nvm exec 4.8.3 node app.js            Run `node app.js` with the PATH pointing to node 4.8.3
  nvm alias default 8.1.0               Set default node version on a shell
  nvm alias default node                Always default to the latest available node version on a shell

  nvm install node                      Install the latest available version
  nvm use node                          Use the latest version
  nvm install --lts                     Install the latest LTS version
  nvm use --lts                         Use the latest LTS version

  nvm set-colors cgYmW                  Set text colors to cyan, green, bold yellow, magenta, and white

Note:
  to remove, delete, or uninstall nvm - just remove the `$NVM_DIR` folder (usually `~/.nvm`)

Обновление энергонезависимой памяти

Мы можем использовать nvm для обновления node.js и npm. Как мы можем обновить сам nvm?

Давай попробуем.

До обновления имеем nvm 0.39.2.

% nvm --version
0.39.2

Обновляем до версии 0.39.3.

% curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 15916  100 15916    0     0    99k      0 --:--:-- --:--:-- --:--:--  105k
=> nvm is already installed in /Users/jenniferfu/.nvm, trying to update using git
=> => Compressing and cleaning up git repository

=> nvm source string already in /Users/jenniferfu/.zshrc
=> bash_completion source string already in /Users/jenniferfu/.zshrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

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

% nvm --version
0.39.3

Заключение

nvm упрощает управление версиями node.js и npm. Мы можем перейти на node.js 20 и npm 9, а также на любые предыдущие версии, перечисленные ниже:

Спасибо за прочтение.

Want to Connect?

If you are interested, check out my directory of web development articles.