Kano001 commited on
Commit
7536d48
1 Parent(s): 6d522a6

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +26 -20
server.js CHANGED
@@ -1,5 +1,5 @@
1
  const WebSocket = require('ws');
2
- const { exec } = require('child_process');
3
 
4
  // Create a WebSocket server listening on port 7860
5
  const wss = new WebSocket.Server({ port: 7860 });
@@ -18,24 +18,30 @@ wss.on('connection', (ws) => {
18
  // Convert message (Buffer) to string
19
  const command = message.toString();
20
 
21
- // Execute the command without sudo
22
- exec(command, (error, stdout, stderr) => {
23
- if (error) {
24
- ws.send(`Error: ${error.message}`);
25
- console.log(`LOG: ${stderr}`);
26
- return;
27
- }
28
- if (stderr) {
29
- ws.send(`stderr: ${stderr}`);
30
- console.log(`LOG: ${stderr}`);
31
- return;
32
- }
33
- if (stdout) {
34
- ws.send(`stdout: ${stdout}`);
35
- console.log(`LOG: ${stdout}`);
36
- return;
37
- }
38
- //ws.send(`stdout: ${stdout}`);
 
 
 
 
 
 
39
  });
40
  });
41
 
@@ -45,4 +51,4 @@ wss.on('connection', (ws) => {
45
  });
46
  });
47
 
48
- console.log('WebSocket server is running on ws://localhost:7860');
 
1
  const WebSocket = require('ws');
2
+ const { spawn } = require('child_process');
3
 
4
  // Create a WebSocket server listening on port 7860
5
  const wss = new WebSocket.Server({ port: 7860 });
 
18
  // Convert message (Buffer) to string
19
  const command = message.toString();
20
 
21
+ // Split command into executable and arguments
22
+ const [cmd, ...args] = command.split(' ');
23
+
24
+ // Spawn a new process to execute the command
25
+ const child = spawn(cmd, args, { shell: true });
26
+
27
+ // Send stdout and stderr to the client
28
+ child.stdout.on('data', (data) => {
29
+ ws.send(`stdout: ${data}`);
30
+ console.log(`stdout: ${data}`);
31
+ });
32
+
33
+ child.stderr.on('data', (data) => {
34
+ ws.send(`stderr: ${data}`);
35
+ console.log(`stderr: ${data}`);
36
+ });
37
+
38
+ child.on('error', (error) => {
39
+ ws.send(`Error: ${error.message}`);
40
+ console.log(`Error: ${error.message}`);
41
+ });
42
+
43
+ child.on('close', (code) => {
44
+ console.log(`Child process exited with code ${code}`);
45
  });
46
  });
47
 
 
51
  });
52
  });
53
 
54
+ console.log('WebSocket server is running on ws://localhost:7860');