forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
104 lines (89 loc) · 2.68 KB
/
Copy pathserver.js
File metadata and controls
104 lines (89 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import express from 'express'
import multer from 'multer'
import path from 'node:path'
import fs from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname } from 'node:path'
import { createProxyMiddleware } from 'http-proxy-middleware'
import {
dcloud,
parseArgv,
colors
} from './util.js'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const arg = parseArgv()
// unicloud 服务空间配置
const spaceInfo = {
spaceId: ``,
clientSecret: ``,
...arg,
}
/**
* 创建 Express 服务器
* @param {number} port - 服务器端口
*/
export function createServer(port = 8800) {
const app = express()
// 确保上传目录存在
const uploadDir = path.join(__dirname, 'public/upload')
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true })
}
// 配置 multer 用于文件上传
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir)
},
filename: (req, file, cb) => {
cb(null, file.originalname)
}
})
const upload = multer({ storage })
// 中间件
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use('/public', express.static(path.join(__dirname, 'public')))
// 文件上传 API
app.post('/upload', upload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' })
}
const file = req.file
let url = `http://127.0.0.1:${port}/public/upload/${file.filename}`
try {
if (spaceInfo.spaceId && spaceInfo.clientSecret) {
url = await dcloud(spaceInfo)({
name: file.originalname,
file: fs.createReadStream(file.path)
})
// 上传成功后删除本地临时文件
fs.unlinkSync(file.path)
console.log('文件已上传到云端:', url)
} else {
console.log(`${colors.yellow('未配置云存储,降级到本地存储')}`)
}
} catch (err) {
// 云上传失败,降级到本地存储
console.log('云存储上传失败,降级到本地存储:', err.message)
}
res.json({ url })
} catch (error) {
console.error('Upload error:', error)
res.status(500).json({ error: error.message })
}
})
console.log('代理到: https://md.doocs.org/')
app.use(createProxyMiddleware({
target: 'https://md.doocs.org/',
changeOrigin: true,
on: {
error: (err, req, res) => {
console.error(`代理错误 ${req.path}:`, err)
res.status(502).send(`代理服务暂不可用,请检查网络连接 ${err.message}`)
},
},
}))
return app
}