first commit

This commit is contained in:
2026-02-14 00:46:04 +08:00
commit 7ce1e58a6e
18 changed files with 2014 additions and 0 deletions

128
backend/js_express.py Normal file
View File

@@ -0,0 +1,128 @@
# -*- coding: utf-8 -*-
"""
JavaScript Express.js 后端项目初始化模块
"""
import subprocess
import sys
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_express_project(backend_dir, project_name):
"""初始化 Express.js 项目"""
print("\n🚀 初始化 Express.js 项目...")
# 初始化 npm 项目
success = run_command_with_progress(
"npm init -y",
backend_dir,
"初始化 npm 项目"
)
if not success:
print("\n💡 提示: 请确保已安装 Node.js 和 npm")
print(" 下载地址: https://nodejs.org/")
sys.exit(1)
# 安装依赖
run_command_with_progress(
"npm install express cors",
backend_dir,
"安装 Express.js 依赖"
)
# 安装开发依赖
run_command_with_progress(
"npm install -D nodemon",
backend_dir,
"安装开发依赖 (nodemon)"
)
# 创建 app.js
app_js = backend_dir / "app.js"
app_js.write_text(f'''const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 8080;
// 中间件
app.use(cors());
app.use(express.json());
// 健康检查接口
app.get('/api/health', (req, res) => {{
res.json({{
status: 'ok',
message: 'Welcome to {project_name} API'
}});
}});
// 示例接口
app.get('/api/hello', (req, res) => {{
res.json({{ message: 'Hello from Express.js!' }});
}});
// 启动服务器
app.listen(PORT, () => {{
console.log('🚀 服务器启动: http://localhost:' + PORT);
console.log('📍 健康检查: http://localhost:' + PORT + '/api/health');
}});
''', encoding='utf-8')
# 更新 package.json 添加脚本
package_json = backend_dir / "package.json"
import json
pkg = json.loads(package_json.read_text(encoding='utf-8'))
pkg['scripts'] = {
'start': 'node app.js',
'dev': 'nodemon app.js'
}
pkg['name'] = f'{project_name}-backend'
package_json.write_text(json.dumps(pkg, indent=2, ensure_ascii=False), encoding='utf-8')
print("\n✅ Express.js 项目初始化成功")
print("💡 启动命令: npm run dev (开发模式) 或 npm start (生产模式)")