This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
child.js
114 lines (93 loc) · 2.63 KB
/
child.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* global Buffer, process */
'use strict';
/**
* Everything.me server for fixtures. Serves stubbed Everything.me responses.
*/
var http = require('http');
var fs = require('fs');
var fsPath = require('path');
var EventEmitter = require('events').EventEmitter;
function writeJSON(res, object) {
object = object || {};
var json = JSON.stringify(object);
res.writeHead(200, {
'Content-Length': Buffer.byteLength(json),
'Content-Type': 'application/json'
});
res.end(json);
}
/**
* @param {String} root directory where content is.@
* @param {Object} routes for the server.
* @constructor
*/
function EmeServer(root, routes) {
EventEmitter.call(this);
// ensure we always have the slash suffix
if (root[root.length - 1] !== '/') {
root += '/';
}
this.root = root;
this.routes = routes;
this._settings = {};
this.fail = false;
}
EmeServer.prototype = {
__proto__: EventEmitter.prototype,
requestHandler: function() {
var routes = this.routes;
return function(req, res) {
// Fail requests
if (req.url.indexOf('/settings') !== 0 && this.fail) {
process.nextTick(function() {
req.socket.destroy();
});
return;
}
var handler = routes[req.url] || routes['*'];
// routes are always invoked with the context of the server.
return handler.call(this, req, res);
}.bind(this);
},
};
var emeServer = new EmeServer(process.argv[2], {
'/Categories/list': function(req, res) {
var json = JSON.parse(fs.readFileSync(this.root + 'categories_list.json'));
writeJSON(res, json);
},
'/Apps/nativeInfo': function(req, res) {
var json = JSON.parse(fs.readFileSync(this.root + 'apps_nativeinfo.json'));
writeJSON(res, json);
},
'/Apps/search': function(req, res) {
var json = JSON.parse(fs.readFileSync(this.root + 'apps_search.json'));
writeJSON(res, json);
},
'/Search/bgimage': function(req, res) {
var json = JSON.parse(fs.readFileSync(this.root + 'search_bgimage.json'));
writeJSON(res, json);
},
'/settings/failAll': function(req, res) {
this.fail = true;
writeJSON(res);
},
'/settings/unfailAll': function(req, res) {
this.fail = false;
writeJSON(res);
},
/**
* Catch all handler which serves up static assets.
*/
'*': function(req, res) {
var url = req.url;
var filePath = fsPath.join(this.root, url);
console.log('Uncaught request: ', url, filePath);
res.writeHead(404);
res.end();
return;
}
});
var server = http.createServer(emeServer.requestHandler());
server.listen(0, function() {
process.send({ type: 'started', port: server.address().port });
});