server.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. const http = require('http');
  2. const querystring = require('querystring');
  3. const url = require('url');
  4. const fs = require('fs');
  5. const path=require('path');
  6. function travel(dir,callback){
  7. fs.readdirSync(dir).forEach((file)=>{
  8. const pathname=path.join(dir,file)
  9. if(fs.statSync(pathname).isDirectory()){
  10. travel(pathname,callback)
  11. }else{
  12. callback(pathname)
  13. }
  14. })
  15. }
  16. function compare(p){ //这是比较函数
  17. return function(m,n){
  18. var a = m[p];
  19. var b = n[p];
  20. return b - a; //降序
  21. }
  22. }
  23. function getDir(){
  24. if(__dirname.indexOf("app") >= 0 && __dirname.indexOf("sources") >= 0){
  25. if(process.platform == "darwin"){
  26. return path.join(__dirname,"../../../..");
  27. } else {
  28. return path.join(__dirname,"../../..");
  29. }
  30. } else{
  31. return __dirname;
  32. }
  33. }
  34. exports.getDir = getDir;
  35. FileMimes = JSON.parse(fs.readFileSync(path.join(__dirname,'mime.json')).toString());
  36. exports.start = function(port = 8074) {
  37. http.createServer(function(req, res) {
  38. let body = "";
  39. res.setHeader("Access-Control-Allow-Origin", "*"); // 设置可访问的源
  40. // 解析参数
  41. const pathName = url.parse(req.url).pathname;
  42. if(pathName.indexOf(".") < 0) { //如果没有后缀名, 则为后台请求
  43. res.writeHead(200, { 'Content-Type': 'application/json' });
  44. }
  45. // else if(pathName.indexOf("index.html") >= 0) {
  46. // fs.readFile(path.join(__dirname,"src", pathName), async (err, data) => {
  47. // if (err) {
  48. // res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' })
  49. // res.end(err.message)
  50. // return;
  51. // }
  52. // if (!err) {
  53. // // 3. 针对不同的文件返回不同的内容头
  54. // let extname = path.extname(pathName);
  55. // let mime = FileMimes[extname]
  56. // res.writeHead(200, { 'Content-Type': mime + ';charset="utf-8"' })
  57. // res.end(data);
  58. // return;
  59. // }
  60. // })
  61. // }
  62. else { //如果有后缀名, 则为前端请求
  63. // console.log(path.join(__dirname,"src/taskGrid", pathName));
  64. fs.readFile(path.join(__dirname,"src", pathName), async (err, data) => {
  65. if (err) {
  66. res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' })
  67. res.end(err.message)
  68. return;
  69. }
  70. if (!err) {
  71. // 3. 针对不同的文件返回不同的内容头
  72. let extname = path.extname(pathName);
  73. let mime = FileMimes[extname]
  74. res.writeHead(200, { 'Content-Type': mime + ';charset="utf-8"' })
  75. res.end(data);
  76. return;
  77. }
  78. })
  79. }
  80. req.on('data', function(chunk) {
  81. body += chunk;
  82. });
  83. req.on('end', function() {
  84. // 设置响应头部信息及编码
  85. if (pathName == "/queryTasks") { //查询所有服务信息,只包括id和服务名称
  86. output = [];
  87. travel(path.join(getDir(), "tasks"),function(pathname){
  88. const data = fs.readFileSync(pathname, 'utf8');
  89. let stat = fs.statSync(pathname, 'utf8');
  90. // parse JSON string to JSON object
  91. const task = JSON.parse(data);
  92. let item = {
  93. "id": task.id,
  94. "name": task.name,
  95. "url": task.url,
  96. "mtime": stat.mtime,
  97. }
  98. if(item.id!= -2) {
  99. output.push(item);
  100. }
  101. });
  102. output.sort(compare("mtime"));
  103. res.write(JSON.stringify(output));
  104. res.end();
  105. } else if (pathName == "/queryExecutionInstances") { //查询所有服务信息,只包括id和服务名称
  106. output = [];
  107. travel(path.join(getDir(), "execution_instances"),function(pathname){
  108. const data = fs.readFileSync(pathname, 'utf8');
  109. // parse JSON string to JSON object
  110. const task = JSON.parse(data);
  111. let item = {
  112. "id": task.id,
  113. "name": task.name,
  114. "url": task.url,
  115. }
  116. if(item.id!= -2) {
  117. output.push(item);
  118. }
  119. });
  120. res.write(JSON.stringify(output));
  121. res.end();
  122. } else if (pathName == "/queryTask") {
  123. var params = url.parse(req.url, true).query;
  124. try {
  125. var tid = parseInt(params.id);
  126. const data = fs.readFileSync(path.join(getDir(), `tasks/${tid}.json`), 'utf8');
  127. // parse JSON string to JSON object
  128. res.write(data);
  129. res.end();
  130. } catch (error) {
  131. res.write(JSON.stringify({ "error": "Cannot find task based on specified task ID." }));
  132. res.end();
  133. }
  134. } else if (pathName == "/queryExecutionInstance") {
  135. var params = url.parse(req.url, true).query;
  136. try {
  137. var tid = parseInt(params.id);
  138. const data = fs.readFileSync(path.join(getDir(), `execution_instances/${tid}.json`), 'utf8');
  139. // parse JSON string to JSON object
  140. res.write(data);
  141. res.end();
  142. } catch (error) {
  143. res.write(JSON.stringify({ "error": "Cannot find execution instance based on specified execution ID." }));
  144. res.end();
  145. }
  146. } else if(pathName == "/"){
  147. res.write("Hello World!", 'utf8');
  148. res.end();
  149. } else if(pathName == "/deleteTask"){
  150. var params = url.parse(req.url, true).query;
  151. try {
  152. let tid = parseInt(params.id);
  153. let data = fs.readFileSync(path.join(getDir(), `tasks/${tid}.json`), 'utf8');
  154. data = JSON.parse(data);
  155. data.id = -2;
  156. data = JSON.stringify(data);
  157. // write JSON string to a file
  158. fs.writeFile(path.join(getDir(), `tasks/${tid}.json`), data, (err) => {
  159. if (err) {
  160. throw err;
  161. }
  162. });
  163. res.write(JSON.stringify({ "success": "Task has been deleted successfully." }));
  164. res.end();
  165. } catch (error) {
  166. res.write(JSON.stringify({ "error": "Cannot find task based on specified task ID." }));
  167. res.end();
  168. }
  169. } else if(pathName == "/manageTask"){
  170. body = querystring.parse(body);
  171. data = JSON.parse(body.paras);
  172. let id = data["id"];
  173. if (data["id"] == -1) {
  174. file_names = [];
  175. fs.readdirSync(path.join(getDir(), "tasks")).forEach((file)=>{
  176. try{
  177. if(file.split(".")[1] == "json"){
  178. file_names.push(parseInt(file.split(".")[0]));
  179. }
  180. } catch (error) {
  181. }
  182. })
  183. if(file_names.length == 0){
  184. id = 0;
  185. } else {
  186. id = Math.max(...file_names) + 1;
  187. }
  188. data["id"] = id;
  189. // write JSON string to a fil
  190. }
  191. data = JSON.stringify(data);
  192. // write JSON string to a file
  193. fs.writeFile(path.join(getDir(), `tasks/${id}.json`), data, (err) => {});
  194. res.write(id.toString(), 'utf8');
  195. res.end();
  196. } else if(pathName == "/invokeTask"){
  197. body = querystring.parse(body);
  198. let data = JSON.parse(body.paras);
  199. let id = body.id;
  200. let task = fs.readFileSync(path.join(getDir(), `tasks/${id}.json`), 'utf8');
  201. task = JSON.parse(task);
  202. try{
  203. task["links"] = data["urlList_0"];
  204. }catch(error){
  205. console.log(error);
  206. }
  207. for (const [key, value] of Object.entries(data)) {
  208. for (let i = 0; i < task["inputParameters"].length; i++) {
  209. if (key === task["inputParameters"][i]["name"]) { // 能调用
  210. const nodeId = parseInt(task["inputParameters"][i]["nodeId"]);
  211. const node = task["graph"][nodeId];
  212. if (node["option"] === 1) {
  213. node["parameters"]["links"] = value;
  214. } else if (node["option"] === 4) {
  215. node["parameters"]["value"] = value;
  216. } else if (node["option"] === 8 && node["parameters"]["loopType"] === 0) {
  217. node["parameters"]["exitCount"] = parseInt(value);
  218. } else if (node["option"] === 8) {
  219. node["parameters"]["textList"] = value;
  220. }
  221. break;
  222. }
  223. }
  224. }
  225. let file_names = [];
  226. fs.readdirSync(path.join(getDir(), "execution_instances")).forEach((file)=>{
  227. try{
  228. if(file.split(".")[1] == "json"){
  229. file_names.push(parseInt(file.split(".")[0]));
  230. }
  231. console.log(file);
  232. } catch (error) {
  233. }
  234. })
  235. let eid = 0;
  236. if (file_names.length != 0) {
  237. eid = Math.max(...file_names) + 1;
  238. }
  239. task["id"] = eid;
  240. task = JSON.stringify(task);
  241. fs.writeFile(path.join(getDir(), `execution_instances/${eid}.json`), task, (err) => {});
  242. res.write(eid.toString(), 'utf8');
  243. res.end();
  244. } else if(pathName == "/getConfig"){
  245. let config = fs.readFileSync(path.join(getDir(), `config.json`), 'utf8');
  246. config = JSON.parse(config);
  247. res.write(JSON.stringify(config));
  248. res.end();
  249. } else if(pathName == "/setUserDataFolder"){
  250. let config = fs.readFileSync(path.join(getDir(), `config.json`), 'utf8');
  251. config = JSON.parse(config);
  252. body = querystring.parse(body);
  253. config["user_data_folder"] = body["user_data_folder"];
  254. config = JSON.stringify(config);
  255. fs.writeFile(path.join(getDir(), `config.json`), config, (err) => {});
  256. res.write(JSON.stringify({ "success": "User data folder has been set successfully." }));
  257. res.end();
  258. }
  259. });
  260. }).listen(port);
  261. console.log("Server has started.");
  262. }