Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
53 lines (45 loc) · 1.5 KB
/
Copy pathserver.js
File metadata and controls
53 lines (45 loc) · 1.5 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
const http = require('http');
const fs = require('fs');
const { exec } = require('child_process');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/code') {
let body = '';
// body 데이터를 chunk 단위로 수집(조각조각 전달될 수 있으니깐)
req.on('data', chunk => {
body += chunk;
});
// body 수집 완료 → 파일 저장 → 실행
req.on('end', () => {
const { code } = JSON.parse(body);
// code 필드가 없으면 에러 응답을 반환
if (!code) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'No code provided' }));
return;
}
// fs 모듈로 temp.py 저장
fs.writeFile('temp.py', code, (writeErr) => {
if (writeErr) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Failed to write file' }));
return;
}
// child_process로 파이썬 실행
exec('python temp.py', (error, stdout, stderr) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
stdout,
stderr,
error: error ? error.message : null,
}));
});
});
});
} else {
res.writeHead(404);
res.end();
}
});
server.listen(3000, () => {
console.log('서버 실행 중');
});