-
Notifications
You must be signed in to change notification settings - Fork 2
/
replace.js
77 lines (63 loc) · 1.87 KB
/
replace.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
/*
* This module checks whether it is necessary to replace the response, based upon an input URI
*/
module.exports = {
proxy: replace
}
var fs = require('fs'),
url = require('url'),
mime = require('mime')
/**
* // in ~/.magicproxyrc:
* replace: [
* {
* replace: 'http://what.to/replace', // You can also use replaceRegExp
* withFile: '/path/to/replacement.js', // You can also use the "with" option, a string containing the file contents.
* contentType: 'content/type', // dafaults to text/plain
* },
* ]
*/
function replace(req, res, plugin) {
var replacements = plugin.config.replace || [];
return replacements.some(function (rep) {
return respond(url.parse(req.url), res, rep);
})
}
function respond(url, res, rep) {
var matches
var re
if (rep.replace) {
matches = url.href === rep.replace
} else if (rep.replaceRegExp) {
re = new RegExp(rep.replaceRegExp)
matches = re.exec(url.href);
}
if (!matches) { return; }
if (re && rep.withFile) {
// replacements
rep.withFile = rep.withFile.replace(/\$(\d)/g, function (_, number) {
return matches[number];
});
}
if (!rep.contentType && rep.withFile) {
rep.contentType = mime.lookup(rep.withFile);
}
var responseStr
if (!rep.with) {
try {
responseStr = fs.readFileSync(rep.withFile)
} catch(e) {
res.statusCode = 404
responseStr = [
'Error loading file', rep.withFile, e].join(' ');
}
} else {
responseStr = rep.with
}
if (!responseStr) {
responseStr = '/* magicProxy: "replace" directive missing "with" or "withFile" options */'
}
res.setHeader('Content-type', rep.contentType || 'text/plain')
res.end(responseStr)
return true; // responded
}