Linux安装node.js并部署前端

270 阅读1分钟

如果使用国外源,可以更改为阿里源

进入yum.repo

cd /etc/yum.repo.d

换成阿里源

wget http://mirrors.aliyun.com/repo/Centos-7.repo

使用EPEL安装nodejs

先确认系统是否已经安装了epel-release包

yum info epel-release

安装epel-release,有了就忽略

yum install epel-release

安装nodejs

yum install nodejs

查看安装版本

node -v

升级nodejs

npm install -g n #n是nodejs的管理工具

安装最新版

n latest

最后键入n来切换版本

如果切换版本失败

vi ~/.bash_profile

将下面两行代码插入到文件末尾

export N_PREFIX=/usr/local #node实际安装位置
export PATH=$N_PREFIX/bin:$PATH

执行source ~/.bash_profile使修改生效,最后键入n

部署前端内容

npm install pm2 -g #全局安装pm2

ln -s /home/bin/pm2 /usr/local/bin/pm2 #创建pm2软链接

编写一个node启动脚本server.js

const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();

app.use(express.static(path.resolve(__dirname, './manage'))) ##这里你项目的名称

app.get('*', function(req, res) {
    const html = fs.readFileSync(path.resolve(__dirname, './manage/index.html'), 'utf-8')
    res.send(html) #index.html的位置
})

app.listen(8002); ##在Web访问的端口

然后再生成一个package.json文件

在文件夹内键入npm init,一路按enter建结束

也可以vi package.json创建

package.json内容为

{
  "name": "back_manage",
  "version": "1.0.0",
  "description": "",
  "main": "server.js", #之前创建的那个文件的名字
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.15.3"
  }
}

最后:一定要将vue项目打包文件,server.js启动脚本,package.json配置文件放在一个文件夹内。三者是同级文件

在文件夹内输入npm install 加载一些配置文件

在项目文件夹里启动server.js

pm2 start server.js

最后用浏览器查询ip地址:8002,查看

pm2的其他命令还有

pm2 show 0(id)//查看某个启动的应用详情
pm2 show list//查看当前启动的所有应用
pm2 stop 0(id)//关闭某个应用