-
Notifications
You must be signed in to change notification settings - Fork 27
/
server.js
219 lines (155 loc) · 5.93 KB
/
server.js
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/*
---------------------
NPM Packages Required
1. Express.js
2. Body-Parser
3. Formidable
4. PythonShell
5. Cors
---------------------
*/
// Import/Require the dependent packages
const express = require("express");
const bodyParser=require("body-parser");
const formidable = require("formidable");
const { PythonShell } = require("python-shell");
const fs = require("fs");
const path = require("path");
const cors = require("cors");
// const process = require('process');
// set up the app using express framework
const app = express();
// setup the global middlewares for the app for accessing static folder
app.use(express.static("public"));
// setup the global middleware for parsing JSON data
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// use cors as a global middleware
app.use(cors());
// import/require the resultant data set information to send back to user
const resultInformation = require("./data");
const uploadDir = path.join(__dirname, "test_images");
// function to delete all files inside test images folder
function deleteFiles(filePath) {
fs.readdir(uploadDir, (err, files) => {
if (err) throw err;
for (let file of files) {
// delete only recently uploaded file
if (file == filePath){
console.log("Deleted!!!");
fs.unlink(path.join(uploadDir, file), err => {
if (err) throw err;
});
}
}
});
}
// Monkey-Patching Technique:
app.use((req, res, next) => {
const render = res.render;
const send = res.send;
res.render = function renderWrapper(...args) {
Error.captureStackTrace(this);
return render.apply(this, args);
};
res.send = function sendWrapper(...args) {
try {
send.apply(this, args);
} catch (err) {
//console.error(`Error in res.send | ${err.code} | ${err.message} | ${res.stack}`);
console.log("Monkey Patching saved the crashing of server here!")
}
};
next();
});
/*
---------------------------------
Routes Setup for the server
---------------------------------
*/
// Index route : @GET method to access
app.get("/", (req, res) => {
res.send("Hello World!");
});
// Wildcard route: @GET method to access (Error/Unwanted routes)
app.get("/*", (req, res) => {
res.send("404! Not found");
});
// Post Route: @POST method to get get back the result from result analysis
/*
@params:{Image} send from the client side
*/
app.post("/file_upload", (req, res, next) => {
// getting service Workers ID's
const id = process.pid;
console.log(`Handled with the service worker of id:${id}`);
// set up the formidable package to handle images from request parameter
const form = formidable({ multiples: true, uploadDir: __dirname + "/test_images", keepExtensions:true});
var fileName, fileType, fileUploadPath;
// parse the incoming request object with multiform type data
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
if(files.file == undefined){
res.send("No Input File");
return;
}
// get access to required file details (name, path and type)
fileName = files.file.name;
fileType = files.file.type;
fileUploadPath = files.file.path;
const newFileName = fileName.split('.').join('-' + Date.now() + '.');
const newPath = __dirname + "/test_images" + "/" + newFileName;
fs.rename(fileUploadPath, newPath, () => {
console.log("Renamed File");
});
// check to support images types
const supportTypes = ["image/jpeg", "image/png", "image/jpg"];
// spawn out python script with required arguments
let options={
args: [newPath]
}
// error check if incoming data is image (with limited types above)
if (supportTypes.includes(fileType)) {
let pythonScript = new PythonShell("label_image.py", options);
// setting timeout race condition against python script:27500 seconds
let pythonKiller = setTimeout(() => {
// kill python script to avoid multiple responses
pythonScript.childProcess.kill();
// send the default result
return res.send(resultInformation("Potato___healthy"));
}, 27500);
// wait for the python script to analyse the image
pythonScript.on('message', (result) => {
console.log(result);
// send the analysed report from the python script
if (result.length !== 0)
res.send(resultInformation(result));
// return: Error messsage if no result is predicted
else
res.json({ Error: "No information found!" });
});
pythonScript.end((err, signal, code) => {
console.log("Python execution was stopped!");
if (err)
console.log("Error from Python", err);
clearTimeout(pythonKiller);
deleteFiles(newFileName);
});
}
// for not supported file types return back with appropriate message
else {
// call the delete method
deleteFiles(newFileName);
res.send({ "Error": "File type not supported! Kindly upload an image!" });
}
});
});
// listen the server at port:3000
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server app listening on port: ${PORT}!`);
console.log(`Worker generated by ID :${process.pid}`);
});