-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js.old
executable file
·168 lines (147 loc) · 4.71 KB
/
index.js.old
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
const { DATA_FILE_FORMAT, DEMOGRAPHICS_FILE_FORMAT, CSV_FORMAT, JSON_FORMAT } = require("./fileformat");
// Dependencies
const express = require("express");
const path = require("path");
const PythonShell = require("python-shell");
const fs = require("fs");
const csvWriter = require("csv-write-stream");
const _ = require("lodash");
const bodyParser = require("body-parser");
const csv = require("csvtojson");
const compression = require('compression');
const jsonfile = require('jsonfile');
let app = express();
let writer = csvWriter({ sendHeaders: false });
app.use(compression())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set("port", process.env.PORT || 7080);
// Add headers
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
// For Rendering HTML
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname + "/dev/index.html"));
});
app.use(express.static(__dirname + "/dev"));
app.listen(app.get("port"), function() {
console.log("Node app is running at http://localhost:" + app.get("port"));
});
// POST endpoint for requesting trials
app.post("/trials", function(req, res) {
console.log("trials post request received");
let subjCode = req.body.workerId;
console.log(req.body);
let trials = [];
fs.readdir('./trials', (err, filenames) => {
let filename = filenames[Math.floor(Math.random()*filenames.length)];
csv({delimiter: ','})
.fromFile('./trials/'+filename)
.on('json',(jsonObj)=>{
trials.push(jsonObj);
})
.on('done',(error)=>{
if (error) {
console.error(error);
throw error;
}
trials.forEach((trial) => {
trial.file = filename;
});
console.log(trials)
res.send({ success: true, trials: trials });
})
})
});
function writeToJSON(req, res, next, folderName) {
// Write response to json
let response = req.body;
let path = `${folderName}/${response.workerId}_${folderName}.json`;
if (!fs.existsSync(path)) {
fs.writeFileSync(path, JSON.stringify({ [folderName]: [] }));
}
console.log('Request body written to ' + path);
jsonfile.readFile(path, (err, obj) => {
if (err) {
res.status(500).send({ success: false });
return next(err);
}
obj[folderName].push(response);
jsonfile.writeFile(path, obj, (err) => {
if (err) {
res.status(500).send({ success: false });
return next(err);
}
res.send({ success: true });
})
})
};
function writeToCSV(req, res, next, folderName) {
// Parses the trial response data to csv
let response = req.body;
let path = `${folderName}/${response.workerId}_${folderName}.csv`;
console.log('Request body written to ' + path);
let headers = Object.keys(response);
if (!fs.existsSync(path)) writer = csvWriter({ headers: headers });
else writer = csvWriter({ sendHeaders: false });
writer.pipe(fs.createWriteStream(path, { flags: "a" }));
writer.write(response);
writer.end();
res.send({ success: true });
}
// POST endpoint for receiving trial responses
app.post('/data', function (req, res, next) {
console.log('data post request received');
// Create new data file if does not exist
let response = req.body;
fs.access('./data', (err) => {
if (err && err.code === 'ENOENT') {
fs.mkdir('./data', () => {
next();
});
}
else next();
});
},
(req, res, next) => {
if (DATA_FILE_FORMAT == JSON_FORMAT) {
writeToJSON(req, res, next, 'data');
} else if (DATA_FILE_FORMAT == CSV_FORMAT) {
writeToCSV(req, res, next, 'data');
} else {
res.status(500).send({ success: false, message: "Invalid file format specified. Check fileformat.js."});
}
});
// POST endpoint for receiving demographics responses
app.post('/demographics', function (req, res, next) {
let demographics = req.body;
console.log('demographics post request received');
console.log(demographics);
fs.access('./demographics', (err) => {
if (err && err.code === 'ENOENT') {
fs.mkdir('./demographics', () => {
next();
});
}
else next();
});
}, (req, res, next) => {
if (DEMOGRAPHICS_FILE_FORMAT == JSON_FORMAT) {
writeToJSON(req, res, next, 'demographics');
} else if (DEMOGRAPHICS_FILE_FORMAT == CSV_FORMAT) {
writeToCSV(req, res, next, 'demographics');
} else {
res.status(500).send({ success: false, message: "Invalid file format specified. Check fileformat.js."});
}
});