-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_sh_server.js
More file actions
executable file
·65 lines (53 loc) · 2.21 KB
/
run_sh_server.js
File metadata and controls
executable file
·65 lines (53 loc) · 2.21 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
const http = require("http");
const { spawn } = require("child_process");
const path = require('path');
const url = require('url');
const fs = require('fs');
const defaultScriptName = 'default.sh';
const scriptFolderPath = path.join(__dirname, 'scripts');
const appPort = 3000;
const requestListener = function (req, res) {
console.log(`Got a request from ${req.connection.remoteAddress}`);
res.setHeader("Content-Type", " text/plain");
res.writeHead(200);
res.write(":: Starting script execution... ::\n\n");
const parsedUrl = url.parse(req.url, true);
const urlPathItems = parsedUrl.pathname.split('/');
const scriptName = urlPathItems[urlPathItems.length - 1] || defaultScriptName;
const scriptPath = path.join(scriptFolderPath, scriptName);
if (!fs.existsSync(scriptPath)) {
res.write("Error: Script not found at path: " + scriptPath);
return res.end()
}
console.log("Running the script: " + scriptPath);
const process = spawn(scriptPath);
process.stdout.on("data", data => {
console.log(`stdout: ${data}`);
res.write(data);
});
process.stderr.on("data", data => {
console.log(`stderr: ${data}`);
res.write(data);
});
process.on('error', (error) => {
console.log(`error: ${error.message}`);
res.write(":: Error occurred: " + error.message );
});
process.on("close", code => {
console.log(`Script exited with code ${code}`);
res.end('\n:: Script execution finished ::');
});
};
http.createServer(requestListener)
.listen(appPort, '0.0.0.0', () => {
console.log(`⚡️ Service is started.`);
console.log(`To run the default script go to: http://localhost:${appPort}`);
console.log(`Do not forget to give execution access, e.g: chmod +x ./scripts/*.sh`);
const scripts = fs.readdirSync(scriptFolderPath, {withFileTypes: true}).filter(item => !item.isDirectory());
if (scripts.length) {
console.log(`\nFounded ${scripts.length} scripts at: ${scriptFolderPath}`);
scripts.map(file => `http://localhost:${appPort}/${file.name}`).forEach(url => console.log(url))
} else {
console.error("No scripts found at: " + scriptFolderPath);
}
});