CentOS9 最新版のnode.jsをインストールする

CentOS9 最新版のnode.jsをインストールする

CentOS9に、最新版のnode.jsをインストールするまでの手順を記述してます。

環境

  • OS  CentOS Stream release 9

標準リポジトリのバージョン確認

先に、標準のリポジトリにある「node.js」のバージョンを確認してみます。

$ dnf info nodejs

名前         : nodejs
エポック     : 1
バージョン   : 16.14.0
リリース     : 5.el9
Arch         : x86_64
サイズ       : 215 k
ソース       : nodejs-16.14.0-5.el9.src.rpm
リポジトリー : appstream
概要         : JavaScript runtime
URL          : http://nodejs.org/
ライセンス   : MIT and ASL 2.0 and ISC and BSD
説明         : Node.js is a platform built on Chrome's JavaScript runtime
             : for easily building fast, scalable network applications.
             : Node.js uses an event-driven, non-blocking I/O model that
             : makes it lightweight and efficient, perfect for data-intensive
             : real-time applications that run across distributed devices.

「16.14.0」で、最新バージョンではなかったので「n package」で最新のnode.jsのインストールを行います。

n package インストール

まずは、必要なパッケージを先にインストールしておきます。

$ sudo dnf install gcc-c++ make

次に「n package」をインストールするために、npmが必要なので、まず「node.js」をインストールします。

$ sudo dnf install -y nodejs

「n package」をインストールします。

$ sudo npm install n -g

<出力結果>
/usr/local/bin/n -> /usr/local/lib/node_modules/n/bin/n
+ n@7.3.0
added 1 package from 2 contributors in 0.468s

「N_PREFIX(nodeモジュールのインストールするPATH)」を追加します。

$ export N_PREFIX=$HOME/.n
$ export PATH=$N_PREFIX/bin:$PATH

永続化するために「bash_profile」にも記述しておきます。

$ sudo nano ~/.bash_profile

export N_PREFIX=$HOME/.n
export PATH=$N_PREFIX/bin:$PATH

再度、実行します。

$ n stable

  installing : node-v16.17.0
       mkdir : /home/testuser/.n/n/versions/node/16.17.0
       fetch : https://nodejs.org/dist/v16.17.0/node-v16.17.0-linux-x64.tar.xz
     copying : node/16.17.0
   installed : v16.17.0 (with npm 8.15.0)

Note: the node command changed location and the old location may be remembered in your current shell.
         old : /usr/bin/node
         new : /home/testuser/.n/bin/node
If "node --version" shows the old version then start a new shell, or reset the location hash with:
hash -r  (for bash, zsh, ash, dash, and ksh)
rehash   (for csh and tcsh)

最初に、インストールした「nodejs」はアンインストールしておきます。

$ sudo dnf remove -y nodejs npm

シェルも再起動しておきます。

$ exec $SHELL -l

node.jsバージョン確認

node.jsのバージョンを確認してみます。

$ node -v

v16.17.0

「16.17.0」になっていることが確認できます。

npmのバージョンも確認しておきます。

$ npm -v

8.15.0

「8.15.0」となってますが、最新ではないので、npmでnpmをアップデートしておきます。

$ npm i -g npm

changed 54 packages, and audited 212 packages in 3s

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

found 0 vulnerabilities

「8.19.1」にアップデートされていることが確認できます。

$ npm -v

8.19.1