腾讯云服务器搭建node环境

步骤一:node环境部署

1.查看系统版本。

[root@VM_0_14_centos ~]# cat /etc/redhat-release

CentOS Linux release 7.6.1810 (Core)
2.下载nodejs-Linux Binaries (x64)压缩包。

[root@VM_0_14_centos ~]# wget https://nodejs.org/dist/v12.16.1/node-v12.16.1-linux-x64.tar.xz

3.查看是否下载了。

[root@VM_0_14_centos ~]# ls

有下面这个xz结尾的文件,证明已经下载。

node-v12.16.1-linux-x64.tar.xz 

4.解压下载的文件 node-v12.16.1-linux-x64.tar.xz 。

[root@VM_0_14_centos ~]# tar xvf node-v12.16.1-linux-x64.tar.xz 

5.解压成功后会得到下面这个文件夹。

node-v12.16.1-linux-x64

6.建立软连,把nodejs环境变为全局环境,这样是为了在任何地方使用node命令。

[root@VM_0_14_centos ~]# ln -s /root/node-v12.16.1-linux-x64/bin/node /usr/local/bin/node
[root@VM_0_14_centos ~]# ln -s /root/node-v12.16.1-linux-x64/bin/npm /usr/local/bin/npm

7.查看node与npm版本。

[root@VM_0_14_centos ~]# node -v
v12.16.1
[root@VM_0_14_centos ~]# npm -v
6.13.4

到这里就已经部署好node环境了。

步骤二:安装nvm控制node多版本(个人意愿)

1.安装git。

[root@VM_0_14_centos ~]# yum install -y git

2.执行以下命令,下载 NVM 源码并检查最新版本。

[root@VM_0_14_centos ~]# git clone https://github.com/cnpm/nvm.git ~/.nvm && cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`

3.执行以下命令,配置 NVM 环境变量。

[root@VM_0_14_centos ~]# echo ". ~/.nvm/nvm.sh" >> /etc/profile

4.执行以下命令,读取环境变量。

[root@VM_0_14_centos ~]# source /etc/profile

5.执行以下命令,查看 Node.js 所有版本。

[root@VM_0_14_centos ~]# nvm list-remote

6.安装多个版本的 Node.js。

[root@VM_0_14_centos ~]# nvm install v10.16.3

7.执行以下命令,查看已安装的 Node.js 版本。

[root@VM_0_14_centos ~]# nvm ls

8.执行以下命令,切换 Node.js 使用版本。

[root@VM_0_14_centos ~]# nvm use v10.16.3

步骤三:创建node项目

1.依次执行以下命令,在根目录创建项目文件 index.js。

cd ~
vim index.js

2.按 “i” 切换至编辑模式,并将以下内容输入 index.js 文件中。

const http = require('http');
const hostname = '0.0.0.0'; // 这里为你服务器内网的ip,记得不是公网ip
const port = 80; // 这里你服务器放通的端口,默认为80,443
const server = http.createServer((req, res) => { 
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/plain');
 res.end('Hello World\n');
}); 
server.listen(port, hostname, () => { 
 console.log(`Server running at http://${hostname}:${port}/`);
});

3.按“Esc”,输入“:wq”,保存文件并返回。
4.执行以下命令,运行 Node.js 项目。

[root@VM_0_14_centos ~]# node index.js

5.在本地浏览器中访问以下地址,查看项目是否正常运行。
注意在浏览器输入的ip地址是公网的ip地址,不是内网的,如果不知道你的公网ip和内网ip,打开腾讯云控制台,查看服务器实例就知道了。

http://公网ip:80/

6.浏览器显示出 helloworld 证明接通了。

祝你成功

发布了7 篇原创文章 · 获赞 17 · 访问量 1900

猜你喜欢

转载自blog.csdn.net/Y00010010/article/details/104671538