在CentOS上构建JS项目通常涉及以下几个步骤:
-
环境准备:
- 更新系统:
sudo yum update -y
- 安装Node.js和npm:
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash - sudo yum install -y nodejs
- 验证安装:
node -v npm -v
- 更新系统:
-
创建项目目录:
mkdir myapp cd myapp
-
初始化项目:
npm init -y
-
安装Express和EJS(如果使用Express框架和EJS模板):
npm install express ejs
-
创建服务器文件: 创建
app.js
并写入以下内容:const express = require('express'); const app = express(); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('index', { title: '首页' }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
-
创建EJS模板: 在项目根目录下创建
views
文件夹,并在其中创建index.ejs
文件: -
配置Nginx反向代理(可选): 编辑Nginx配置文件:
sudo vi /etc/nginx/nginx.conf
在http块中添加以下配置:
server { listen 80; server_name yourdomain.com; location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
重启Nginx:
sudo systemctl restart nginx
-
启动项目:
node app.js
通过以上步骤,你可以在CentOS上成功构建并运行一个基本的Node.js项目。