-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.js
83 lines (71 loc) · 2.4 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
var sys = require('sys'),
path = require('path'),
http = require('http'),
formidable = require('./lib/formidable'),
paperboy = require('./lib/paperboy');
var PUBLIC = path.join(path.dirname(__filename), 'public');
var progresses = {}
var metadata = {}
http.createServer(function(req, res) {
// parse an upload using formidable.
regex = new RegExp('/upload/(.+)');
match = regex.exec(req.url);
if (match && req.method.toLowerCase() == 'post') {
var uuid = match[1];
sys.print("receiving upload: "+uuid+'\n');
var form = new formidable.IncomingForm();
form.uploadDir = './data';
form.keepExtensions = true;
// keep track of progress.
form.addListener('progress', function(recvd, expected) {
progress = (recvd / expected * 100).toFixed(2);
progresses[uuid] = progress
});
form.parse(req, function(error, fields, files) {
var path = files['file']['path'],
filename = files['file']['filename'],
mime = files['file']['mime'];
res.writeHead(200, {'content-type': 'text/html'});
res.write('<textarea>');
res.write("upload complete.\n");
res.write(filename + ' landed safely at ' + path + '\n');
res.write('</textarea>')
res.end()
sys.print("finished upload: "+uuid+'\n');
});
return;
}
// (update) metadata
regex = new RegExp('/update/(.+)');
match = regex.exec(req.url);
if (match && req.method.toLowerCase() == 'post') {
uuid = match[1]
var form = new formidable.IncomingForm();
form.addListener('field', function(name, value) {
sys.print("fresh metadata for "+uuid+": "+name+" => "+value+"\n")
metadata[name] = value;
});
form.parse(req);
}
// respond to progress queries.
regex = new RegExp('/progress/(.+)');
match = regex.exec(req.url);
if (match) {
uuid = match[1];
res.writeHead(200, {'content-type': 'application/json'});
res.write(JSON.stringify({'progress': progresses[uuid]}));
res.end();
}
// let paperboy handle any static content.
paperboy
.deliver(PUBLIC, req, res)
.after(function(statCode) {
sys.log('Served Request: ' + statCode + ' ' + req.url)
})
.otherwise(function() {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write('Not Found');
res.end();
});
}).listen(8000, '127.0.0.1');
sys.log('ready at http://localhost:8000/')