-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.js
More file actions
73 lines (57 loc) · 2.18 KB
/
Copy pathhandlers.js
File metadata and controls
73 lines (57 loc) · 2.18 KB
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
var config = require('./config'),
fs = require('fs');
function home(response, postData) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(fs.readFileSync('./static/index.html'));
}
function upload(response, postData) {
var file = JSON.parse(postData),
fileRootName = file.name.split('.').shift(),
fileExtension = file.name.split('.').pop(),
filePathBase = config.upload_dir + '/',
fileRootNameWithBase = filePathBase + fileRootName,
filePath = fileRootNameWithBase + '.' + fileExtension,
fileID = 2,
fileBuffer;
while (fs.existsSync(filePath)) {
filePath = fileRootNameWithBase + '(' + fileID + ').' + fileExtension;
fileID += 1;
}
file.contents = file.contents.split(',').pop();
fileBuffer = new Buffer(file.contents, "base64");
if (config.s3_enabled) {
var knox = require('knox'),
client = knox.createClient(config.s3),
headers = {'Content-Type': file.type};
client.putBuffer(fileBuffer, fileRootName, headers, function (err, res) {
if (typeof res !== "undefined" && 200 === res.statusCode) {
console.log('Uploaded to: %s', res.client._httpMessage.url);
response.statusCode = 200;
} else {
console.log('Upload failed!');
response.statusCode = 500;
}
response.end();
});
} else {
fs.writeFileSync(filePath, fileBuffer);
response.statusCode = 200;
response.end();
}
}
function serveStatic(response, pathname, postData) {
var extension = pathname.split('.').pop(),
extensionTypes = {
'css' : 'text/css',
'gif' : 'image/gif',
'jpg' : 'image/jpeg',
'jpeg': 'image/jpeg',
'js' : 'application/javascript',
'png' : 'image/png'
};
response.writeHead(200, {'Content-Type': extensionTypes[extension]});
response.end(fs.readFileSync('./static' + pathname));
}
exports.home = home;
exports.upload = upload;
exports.serveStatic = serveStatic;