-
Notifications
You must be signed in to change notification settings - Fork 2
/
fakeDir.js
98 lines (84 loc) · 2.53 KB
/
fakeDir.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
/*
* Fakes a server directory with static files, but serves files from a local dir.
*/
module.exports = {
proxy: fakeDirProxy
}
var fs = require('fs'),
url = require('url'),
path = require('path'),
mime = require('mime')
/**
* // in ~/.magicproxyrc:
* fakeDir: [
* {
* url: 'http://my-site.com/static/js',
* dir: '/path/to/local/js/folder',
* contentType: 'content/type', // dafaults to text/plain
* },
* ]
*/
function fakeDirProxy(req, res, plugin) {
var remoteUrl = url.parse(req.url)
var operations = plugin.config.fakeDir || []
var fakeDir = findOp(req, operations)
if (!fakeDir) {
return false;
}
var relativePath = path.relative(fakeDir.url, req.url.replace(/\??.*?/, ''))
var absPath = path.join(fakeDir.dir, relativePath)
if (!fakeDir.contentType) {
fakeDir.contentType = mime.lookup(absPath) || 'text/plain';
if (fakeDir.contentType === 'application/javascript') {
fakeDir.contentType = 'text/javascript';
}
}
if (absPath.match(/\.js$/)) {
fakeDir.contentType = 'text/javascript';
}
if (absPath.match(/\.css$/)) {
fakeDir.contentType = 'text/css';
}
if (absPath.match(/\.html$/)) {
fakeDir.contentType = 'text/html';
}
if (absPath.match(/\.txt$/)) {
fakeDir.contentType = 'text/plain';
}
respondWith(fakeDir, res, absPath);
return true;
}
function findOp(req, operations) {
for (var i = 0, len = operations.length; i < len; i++) {
if (req.url.indexOf(operations[i].url) === 0) {
return operations[i]
}
}
return null;
}
function respondWith(fakeDir, res, absPath) {
res.setHeader('Content-Type', fakeDir.contentType)
res.setHeader('Access-Control-Allow-Origin', '*')
fs.readFile(absPath, function (err, data) {
if (err) {
// Error could be that the user is looking at a dir.
// Servers have index files for that.
if (err.code !== 'EISDIR' || !fakeDir.indexFile) {
return onIOError(res, err);
} else {
var index = fakeDir.indexFile;
index = path.join(absPath, index)
return respondWith(fakeDir, res, index)
}
}
res.end(data)
})
}
function onIOError(res, err) {
res.setHeader('Content-Type', 'text/plain')
res.statusCode = 404
res.write('MagicProxy fakeDir IO error');
console.error(err);
res.write(err.toString());
return res.end()
}