-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode-executor.js
More file actions
73 lines (61 loc) · 1.84 KB
/
Copy pathcode-executor.js
File metadata and controls
73 lines (61 loc) · 1.84 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
const { spawn, exec } = require('child_process');
const vm = require('vm');
const fs = require('fs');
const path = require('path');
class CodeExecutor {
constructor() {
this.timeout = 10000;
}
async execute(language, code) {
switch (language) {
case 'javascript':
return await this.executeJavaScript(code);
case 'python':
return await this.executePython(code);
default:
throw new Error(`Unsupported language: ${language}`);
}
}
async executeJavaScript(code) {
return new Promise((resolve, reject) => {
let output = '';
try {
const sandbox = {
console: {
log: (...args) => {
output += args.join(' ') + '\n';
}
}
};
vm.createContext(sandbox);
vm.runInContext(code, sandbox, {
timeout: this.timeout,
displayErrors: true
});
resolve(output || 'Code executed successfully (no output)');
} catch (error) {
reject(error);
}
});
}
async executePython(code) {
return new Promise((resolve, reject) => {
const tempFilePath = path.join(__dirname, 'temp_script.py');
try {
fs.writeFileSync(tempFilePath, code);
} catch (err) {
return reject(new Error(`Failed to write temp file: ${err.message}`));
}
// Command to open a new CMD window, run the script, and pause so output is visible
const command = `start cmd /c "python "${tempFilePath}" & echo. & echo Press any key to close... & pause"`;
exec(command, (error) => {
if (error) {
reject(new Error(`Failed to launch CMD: ${error.message}`));
} else {
resolve('Code executing in a new CMD window on the remote machine.');
}
});
});
}
}
module.exports = CodeExecutor;