forked from etaub47/tracking-pixel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
95 lines (81 loc) · 2.06 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
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Dummy Server
*
* Acts like the TA Pixel servlet for rapid testing
*
* @author mtownsend
* @since Dec 2015
**/
'use strict';
var PORT = 80;
var http = require('http')
, query = require('querystring')
, Promise = require('promise')
, path = require('path')
, fs = require('fs')
, server = http.createServer(handleRequest)
;
function processPost(req, res) {
return new Promise(function(accept, reject) {
var queryData = '';
if (req.method !== 'POST') {
res.writeHead(405, { 'Content-Type': 'text/plain' }).end();
reject();
return;
}
req.on('data', function(data) {
queryData += data;
if (queryData.length > 1e6) {
queryData = '';
res.writeHead(413, {'Content-Type': 'text/plain'}).end();
req.connection.destroy();
reject();
}
});
req.on('end', function() {
accept(query.parse(queryData));
});
});
}
function serveFile(req, res) {
var filePath = '.' + req.url
, ext
, type
;
if (filePath === './') { filePath = './test.html' }
ext = path.extname(filePath);
if (ext === '.js') {
type = 'text/javascript';
}
type = ext === '.js' ? 'text/javascript' : 'text/html';
fs.readFile(filePath, function(error, content) {
if (error) {
res.writeHead(404, { 'Content-Type': type });
res.end();
}
else {
res.writeHead(200, {
'Content-Type': type,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'
});
res.end(content, 'utf-8');
}
});
}
function handleRequest(req, res) {
if (req.method === 'POST') {
processPost(req, res).then(function (data) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'
});
res.write(JSON.stringify(data));
res.end();
});
} else {
serveFile(req, res);
}
}
server.listen(PORT, function() { console.log('server listening on port ' + PORT); });