-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.js
66 lines (56 loc) · 2 KB
/
app.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
/* global require:true, console:true, process:true, __dirname:true */
'use strict'
// Example run command: `node app.js 9000 6380 true`; listen on port 9000, connect to redis on 6380, debug printing on.
var express = require('express')
, http = require('http')
, redis = require('redis')
, redisClient
, port = process.argv[2] || 8000
, rport = process.argv[3] || 6379
, debug = process.argv[4] || null
// Database setup
redisClient = redis.createClient(rport)
redisClient.on('connect', function() {
console.log('Connected to redis.')
})
// Data handling
var save = function save(d) {
redisClient.hmset(d.postId, {"content": JSON.stringify(d)})
if( debug )
console.log('saved to redis: ' + d.postId +', at: '+ (new Date()).toString())
}
// Server setup
var app = express()
app.use(express.bodyParser())
app.use(express.static(__dirname + '/public'))
app.use('/scripts', express.static(__dirname + '/node_modules/'));
// If the study has finished, write the data to file
app.post('/finish', function(req, res) {
fs.readFile('public/modules/consent/blocked-workers.json', 'utf8', function(err,data) {
if (err) console.log(err);
var data = JSON.parse(data);
data.push(req.body.workerId);
data = JSON.stringify(data);
fs.writeFile('public/modules/consent/blocked-workers.json', data, function(err) {
if(err) console.log(err);
});
});
res.send(200)
})
// Handle POSTs from frontend
app.post('/', function handlePost(req, res) {
// Get experiment data from request body
var d = req.body
// If a postId doesn't exist, add one (it's random, based on date)
if (!d.postId) d.postId = (+new Date()).toString(36)
// Add a timestamp
d.timestamp = (new Date()).getTime()
// Save the data to our database
save(d)
// Send a 'success' response to the frontend
res.send(200)
})
// Create the server and tell which port to listen to
http.createServer(app).listen(port, function (err) {
if (!err) console.log('Listening on port ' + port)
})