-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
58 lines (52 loc) · 1.94 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
var http = require('http');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/'));
var responses = [];
var files = [];
app.get('/content/:filename', function(request, response) {
if (files.indexOf(request.params.filename) === -1) {
response.writeHead('404');
response.end('Resource not found or has already downloaded once');
return false;
}
response.writeHead(200);
console.log('Requested file: ' + request.params.filename);
responses[request.params.filename] = response;
});
app.get('/download/:filename.html', function(request, response) {
if (files.indexOf(request.params.filename) === -1) {
response.writeHead('404');
response.end('Resource not found or has already downloaded once');
return false;
}
response.setHeader('Content-Type', 'text/html');
response.end('File ' +
request.params.filename +
' is ready for download. <a href="/content/' +
request.params.filename + '">Get it</a>');
});
var server = http.createServer(app);
var BinaryServer = require('binaryjs').BinaryServer;
var bs = BinaryServer({server: server});
bs.on('connection', function(client) {
client.on('stream', function(stream, meta) {
if (files.indexOf(meta.name) < 0) {
files.push(meta.name);
}
if (responses[meta.name]) {
delete files[files.indexOf(meta.name)];
console.log('Transfer of file ' + meta.name + ' started');
stream.pipe(responses[meta.name], {end: false});
stream.on('end', function() {
responses[meta.name].end();
console.log('Transfer of file ' + meta.name + ' finished');
});
stream.on('data', function(data) {
stream.write({rx: data.length / meta.size});
});
}
});
});
server.listen(9000);
console.log('Server started on port 9000');