从 Linux Yum 存储库安装 Node.js
在 CentOS/RHEL 8 上安装 Node.js 的最简单方法是使用 Linux yum 存储库。
在 CentOS 8 yum 存储库中,Node.js 的两个稳定版本已经可用。
这些是最常用的版本,可以在大多数情况下使用。
要获取 Linux yum 存储库中 Node.js 的可用版本列表,我们可以使用以下 dnf 命令。
# dnf module list nodejs Last metadata expiration check: 0:07:05 ago on Wed 18 Nov 2020 09:43:56 PM PKT. CentOS-8 - AppStream Name Stream Profiles Summary nodejs 10 [d] common [d], development, minimal, s2i Javascript runtime nodejs 12 common [d], development, minimal, s2i Javascript runtime Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled
使用 dnf 命令安装所需的 Node.js 版本,我们将在 Linux 服务器上安装版本 12.
# dnf module install -y nodejs:12
安装成功后,检查 Node.js 版本和 Node Package Manager (NPM) 版本。
# node -v v12.18.4 # npm -v 6.14.6
创建和部署一个简单的 Node.js 应用程序
我们可以通过编写一个简单的 JavaScript 来测试 Node.js 服务器。
在 vim 编辑器中创建一个文本文件。
# vi Node.js_test.js
在此文件中添加以下代码行。
const http = require('http'); const port = 9000; const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }); server.listen(port, () => { console.log(`Server running at http://your-ip-address:${port}/`); });
暂时允许 Linux 防火墙中的服务端口 9000/tcp。
# firewall-cmd --add-port=9000/tcp success
使用以下命令启动 Node.js 调试器进程。
# node --inspect Node.js_test.js Debugger listening on ws://127.0.0.1:9229/d25c2fe9-b50e-4bfb-aa45-1d6988d5d470 For help, see: https://nodejs.org/en/docs/inspector Server running at http://your-ip-address:9000/
使用 Web 浏览器或者遵循 Linux 命令来测试 Node.js 应用程序。
# curl http://nodejs-01.onitroad.com:9000 Hello World
使用 NVM 安装 Node.js
尽管从 Linux yum 存储库安装 Node.js 非常方便。
但是我们可能没有其中找到最新版本的 Node.js。
例如,Node.js 版本 14 LTS 和 15 已经发布,但它们在 Linux yum 存储库中不可用。
因此,如果我们希望安装最新版本的 Node.js,那么我们必须使用 Node Version Manager (NVM)。
通过使用 NVM,我们可以轻松地在 Linux 服务器上安装/卸载不同版本的 Node.js。
NVM 可在 GitHub 上获得。
我们可以在 NVM Github 存储库中查看完整的项目详细信息。
我们可以使用 NVM 文档中提供的脚本安装 NVM。
# curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.0/install.sh | bash
NVM 已安装,我们现在可以使用 nvm 命令在 Linux 服务器上安装 Node.js。
但首先,列出 Node.js 的可用版本。
# nvm list-remote ... v14.14.0 v14.15.0 (LTS: Fermium) v14.15.1 (Latest LTS: Fermium) v15.0.0 ...
虽然 Node.js v15 可用,但它是安装 LTS(长期支持)版本的更好方法,尤其是当我们在生产机器上安装 Node.js 时。
我们可以使用 nvm 命令安装最新的 LTS 版本的 Node.js。
# nvm install --lts
验证已安装的 Node.js 和 Node Package Manager (NPM) 版本。
# node -v v14.15.1 # npm -v 6.14.8
同样,我们可以使用 NVM 切换到另一个版本的 Node.js,如下所示。
# nvm install v13.6.0 Downloading and installing node v13.6.0... Downloading https://nodejs.org/dist/v13.6.0/node-v13.6.0-linux-x64.tar.xz... ######################################################################### 100.0% Computing checksum with sha256sum Checksums matched! Now using node v13.6.0 (npm v6.13.4)
再次检查已安装的 Node.js 和 NPM 版本。
# node -v v13.6.0 # npm -v 6.13.4
Node.js 是一个开源、跨平台、后端、JavaScript 运行时环境,可在 Web 浏览器之外执行 JavaScript 代码。
在本教程中,我们将学习如何在基于 CentOS/RHEL 8 的服务器上安装它。