-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
399 lines (364 loc) · 13.6 KB
/
Copy pathserver.js
File metadata and controls
399 lines (364 loc) · 13.6 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
const express = require('express');
const fs = require('fs');
const path = require('path');
const { execSync, spawn } = require('child_process');
const app = express();
const PORT = 3456;
// ---- 工具路径 ----
const TOOLS = {
python: 'python',
python3: 'python3',
node: 'node',
javac: 'javac',
java: 'java',
gcc: 'gcc',
gpp: 'g++',
bash: 'bash',
};
// 运行时缓存
const toolCache = {};
function findTool(name) {
if (toolCache[name] !== undefined) return toolCache[name];
try {
let out;
// Java 特殊处理:先找真实 JDK 而不是 Oracle javapath 的 shim
if (name === 'javac' || name === 'java') {
const javaHome = process.env.JAVA_HOME;
if (javaHome) {
const jhBin = path.join(javaHome, 'bin', name + '.exe');
if (fs.existsSync(jhBin)) {
toolCache[name] = jhBin.replace(/\\/g, '/');
return toolCache[name];
}
}
// 搜索常见 JDK 路径
const searchDirs = [
'C:/Program Files/Java', 'C:/Program Files (x86)/Java',
'D:/Java', 'D:/JDK'
];
for (const base of searchDirs) {
if (!fs.existsSync(base)) continue;
const entries = fs.readdirSync(base, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory() || !entry.name.toLowerCase().startsWith('jdk')) continue;
const bin = path.join(base, entry.name, 'bin', name + '.exe');
if (fs.existsSync(bin)) {
toolCache[name] = bin.replace(/\\/g, '/');
return toolCache[name];
}
}
}
}
// 通用:用 which 从 PATH 找
out = execSync(`which ${name} 2>/dev/null || command -v ${name} 2>/dev/null`, {
encoding: 'utf-8', shell: 'bash', timeout: 5000
}).trim();
const winPath = out ? out.replace(/^\/([a-z])\//i, (_, d) => d.toUpperCase() + ':/') : null;
toolCache[name] = winPath || null;
return toolCache[name];
} catch (e) {
toolCache[name] = null;
return null;
}
}
app.use(express.json({ limit: '10mb' }));
app.use(express.static(__dirname));
// 本地 CodeMirror — 不依赖 CDN
app.use('/cm', express.static(path.join(__dirname, 'node_modules/codemirror')));
// ----- 文件列表 API -----
app.post('/api/list', (req, res) => {
const { dirPath } = req.body;
const absPath = path.resolve(dirPath || __dirname);
try {
if (!fs.existsSync(absPath)) return res.json({ ok: false, msg: '路径不存在: ' + absPath });
const items = fs.readdirSync(absPath).map(name => {
const full = path.join(absPath, name);
let stat;
try { stat = fs.statSync(full); } catch (e) { return null; }
return {
name,
path: full.replace(/\\/g, '/'),
isDir: stat.isDirectory(),
size: stat.size,
mtime: stat.mtime.toISOString()
};
}).filter(Boolean).sort((a, b) => {
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
return a.name.localeCompare(b.name, 'zh');
});
res.json({ ok: true, items, dirPath: absPath.replace(/\\/g, '/') });
} catch (e) {
res.json({ ok: false, msg: e.message });
}
});
// ----- 读取文件 -----
app.post('/api/read', (req, res) => {
const { filePath } = req.body;
const absPath = path.resolve(filePath);
try {
if (!fs.existsSync(absPath)) return res.json({ ok: false, msg: '文件不存在' });
const stat = fs.statSync(absPath);
if (stat.isDirectory()) return res.json({ ok: false, msg: '这是文件夹' });
if (stat.size > 5 * 1024 * 1024) return res.json({ ok: false, msg: '文件超过 5MB' });
const content = fs.readFileSync(absPath, 'utf-8');
const ext = path.extname(absPath).slice(1).toLowerCase();
const langMap = {
js: 'javascript', mjs: 'javascript', cjs: 'javascript',
ts: 'text/typescript', jsx: 'javascript', tsx: 'text/typescript',
py: 'python', pyw: 'python',
html: 'htmlmixed', htm: 'htmlmixed',
css: 'css', scss: 'text/x-scss', less: 'text/x-less',
json: 'application/json', xml: 'xml', md: 'gfm',
sql: 'text/x-sql',
java: 'text/x-java',
c: 'text/x-csrc', h: 'text/x-csrc',
cpp: 'text/x-c++src', cc: 'text/x-c++src', cxx: 'text/x-c++src', hpp: 'text/x-c++src',
cs: 'text/x-csharp',
go: 'go', rs: 'rust', php: 'php', rb: 'ruby', swift: 'swift',
kt: 'text/x-kotlin',
sh: 'shell', bash: 'shell', zsh: 'shell', bat: 'shell', ps1: 'shell',
yml: 'yaml', yaml: 'yaml', toml: 'toml', ini: 'properties',
txt: 'text', log: 'text',
vue: 'htmlmixed', svelte: 'htmlmixed'
};
res.json({
ok: true, content,
lang: langMap[ext] || 'text',
name: path.basename(absPath),
path: absPath.replace(/\\/g, '/')
});
} catch (e) {
res.json({ ok: false, msg: e.message });
}
});
// ----- 保存文件 -----
app.post('/api/save', (req, res) => {
const { filePath, content } = req.body;
const absPath = path.resolve(filePath);
try {
const dir = path.dirname(absPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(absPath, content, 'utf-8');
res.json({ ok: true });
} catch (e) {
res.json({ ok: false, msg: e.message });
}
});
// ----- 创建文件/文件夹 -----
app.post('/api/create', (req, res) => {
const { parentPath, name, isDir } = req.body;
const fullPath = path.join(path.resolve(parentPath), name);
try {
if (fs.existsSync(fullPath)) return res.json({ ok: false, msg: '已存在同名文件/文件夹' });
if (isDir) {
fs.mkdirSync(fullPath, { recursive: true });
} else {
const dir = path.dirname(fullPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(fullPath, '', 'utf-8');
}
res.json({ ok: true, path: fullPath.replace(/\\/g, '/') });
} catch (e) {
res.json({ ok: false, msg: e.message });
}
});
// ----- 删除文件/文件夹 -----
app.post('/api/delete', (req, res) => {
const { targetPath } = req.body;
const absPath = path.resolve(targetPath);
try {
if (!fs.existsSync(absPath)) return res.json({ ok: false, msg: '路径不存在' });
const stat = fs.statSync(absPath);
if (stat.isDirectory()) {
fs.rmSync(absPath, { recursive: true, force: true });
} else {
fs.unlinkSync(absPath);
}
res.json({ ok: true });
} catch (e) {
res.json({ ok: false, msg: e.message });
}
});
// ----- 重命名 -----
app.post('/api/rename', (req, res) => {
const { oldPath, newName } = req.body;
const absOld = path.resolve(oldPath);
const absNew = path.join(path.dirname(absOld), newName);
try {
if (!fs.existsSync(absOld)) return res.json({ ok: false, msg: '原路径不存在' });
if (fs.existsSync(absNew)) return res.json({ ok: false, msg: '目标名称已存在' });
fs.renameSync(absOld, absNew);
res.json({ ok: true, newPath: absNew.replace(/\\/g, '/') });
} catch (e) {
res.json({ ok: false, msg: e.message });
}
});
// ----- 获取磁盘列表 -----
app.get('/api/drives', (req, res) => {
try {
const result = execSync('wmic logicaldisk get name', { encoding: 'utf-8', timeout: 5000 });
const drives = result.split('\n').map(l => l.trim()).filter(l => /^[A-Z]:$/.test(l)).map(d => d + '/');
res.json({ ok: true, drives: drives.length ? drives : ['C:/'] });
} catch (e) {
res.json({ ok: true, drives: ['C:/'] });
}
});
// ----- 检测可用工具 -----
app.get('/api/tools', (req, res) => {
const available = {};
for (const [name, cmd] of Object.entries(TOOLS)) {
available[name] = !!findTool(cmd);
}
res.json({ ok: true, tools: available });
});
// ============ 代码运行核心 ============
function spawnProc(command, args, cwd, timeout = 30000) {
return new Promise((resolve) => {
let output = '';
let errorOutput = '';
try {
// 使用 shell: false 避免路径空格问题,直接 spawn 可执行文件
const proc = spawn(command, args, {
cwd,
shell: false,
timeout,
windowsHide: true,
env: { ...process.env, PYTHONIOENCODING: 'utf-8' }
});
proc.stdout.on('data', (data) => {
output += data.toString();
if (output.length > 1024 * 1024) {
output += '\n[输出超过 1MB,已截断]';
proc.kill();
}
});
proc.stderr.on('data', (data) => {
errorOutput += data.toString();
});
proc.on('close', (code) => {
const combined = output + (errorOutput ? (output ? '\n' : '') + errorOutput : '');
resolve({
exitCode: code,
output: combined || (code === 0 ? '(无输出)' : `(退出码: ${code})`),
ok: code === 0
});
});
proc.on('error', (err) => {
resolve({ exitCode: null, output: '进程启动失败: ' + err.message, ok: false });
});
} catch (e) {
resolve({ exitCode: null, output: '执行失败: ' + e.message, ok: false });
}
});
}
// ============ 代码运行 API ============
app.post('/api/run', (req, res) => {
const { filePath, lang } = req.body;
const absPath = path.resolve(filePath);
const dir = path.dirname(absPath);
const baseName = path.basename(absPath);
const nameNoExt = baseName.replace(/\.[^.]+$/, '');
try {
if (!fs.existsSync(absPath))
return res.json({ ok: false, output: '文件不存在: ' + absPath });
switch (lang) {
case 'python': return runPython(absPath, dir, res);
case 'javascript': return runNode(absPath, dir, res);
case 'text/typescript': return runNode(absPath, dir, res);
case 'text/x-java': return runJava(absPath, dir, nameNoExt, res);
case 'text/x-csrc': return runC(absPath, dir, nameNoExt, res);
case 'text/x-c++src': return runCpp(absPath, dir, nameNoExt, res);
case 'htmlmixed': return runHtml(absPath, res);
case 'shell': return runShell(absPath, dir, res);
default:
return res.json({
ok: false,
output: '不支持运行此语言: ' + lang +
'\n\n支持的语言: Python | JavaScript/TypeScript | Java | C | C++ | HTML | Shell'
});
}
} catch (e) {
res.json({ ok: false, output: '执行异常: ' + e.message });
}
});
function runPython(absPath, cwd, res) {
const py = findTool('python3') || findTool('python');
if (!py) return res.json({ ok: false, output: '未找到 Python 解释器。请安装 Python 并添加到 PATH。' });
spawnProc(py, ['-u', absPath], cwd).then(r => res.json(r));
}
function runNode(absPath, cwd, res) {
const node = findTool('node');
if (!node) return res.json({ ok: false, output: '未找到 Node.js。' });
spawnProc(node, [absPath], cwd).then(r => res.json(r));
}
function runJava(absPath, cwd, nameNoExt, res) {
const javac = findTool('javac');
const java = findTool('java');
if (!javac || !java)
return res.json({ ok: false, output: '未找到 JDK。请安装 Java JDK 并添加到 PATH。\n下载: https://adoptium.net' });
// 编译 — 使用 spawn 避免 execSync 的路径转义问题
spawnProc(javac, ['-encoding', 'UTF-8', absPath], cwd, 15000).then(compileResult => {
if (!compileResult.ok) {
return res.json({ ok: false, output: '编译失败:\n' + compileResult.output });
}
// 运行
spawnProc(java, ['-Dfile.encoding=UTF-8', '-cp', cwd, nameNoExt], cwd).then(r => {
try { fs.unlinkSync(path.join(cwd, nameNoExt + '.class')); } catch (e) {}
res.json(r);
});
});
}
function runC(absPath, cwd, nameNoExt, res) {
const gcc = findTool('gcc');
if (!gcc) return res.json({ ok: false, output:
'未找到 GCC 编译器。\n\n安装 MinGW-w64:\n 1. 下载 https://winlibs.com\n 2. 解压后将 bin 目录加入 PATH\n 3. 重启终端' });
const exePath = path.join(cwd, nameNoExt + '.exe');
spawnProc(gcc, ['-Wall', '-o', exePath, absPath], cwd, 15000).then(compileResult => {
if (!compileResult.ok) {
try { fs.unlinkSync(exePath); } catch (e) {}
return res.json({ ok: false, output: '编译失败:\n' + compileResult.output });
}
spawnProc(exePath, [], cwd).then(r => {
try { fs.unlinkSync(exePath); } catch (e) {}
res.json(r);
});
});
}
function runCpp(absPath, cwd, nameNoExt, res) {
const gpp = findTool('g++');
if (!gpp) return res.json({ ok: false, output:
'未找到 G++ 编译器。\n\n安装 MinGW-w64:\n 1. 下载 https://winlibs.com\n 2. 解压后将 bin 目录加入 PATH\n 3. 重启终端' });
const exePath = path.join(cwd, nameNoExt + '.exe');
spawnProc(gpp, ['-Wall', '-std=c++17', '-o', exePath, absPath], cwd, 15000).then(compileResult => {
if (!compileResult.ok) {
try { fs.unlinkSync(exePath); } catch (e) {}
return res.json({ ok: false, output: '编译失败:\n' + compileResult.output });
}
spawnProc(exePath, [], cwd).then(r => {
try { fs.unlinkSync(exePath); } catch (e) {}
res.json(r);
});
});
}
function runHtml(absPath, res) {
res.json({ ok: true, output: '', previewUrl: '/preview?file=' + encodeURIComponent(absPath) });
}
app.get('/preview', (req, res) => {
const f = req.query.file;
if (!f) return res.send('<p>缺少参数</p>');
const ap = path.resolve(f);
try {
if (!fs.existsSync(ap)) return res.send('<p>文件不存在</p>');
res.send(fs.readFileSync(ap, 'utf-8'));
} catch (e) {
res.send('<p>读取失败: ' + e.message + '</p>');
}
});
function runShell(absPath, cwd, res) {
const bash = findTool('bash') || 'bash';
spawnProc(bash, [absPath], cwd).then(r => res.json(r));
}
app.listen(PORT, () => {
console.log('VSCode Mini Pro 运行在 http://localhost:' + PORT);
console.log('支持: Python | JavaScript | TypeScript | Java | C | C++ | HTML | Shell');
});