-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstatico.js
87 lines (64 loc) · 1.87 KB
/
statico.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
var fs = require('fs');
var path = require('path');
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
function setuper(req, res) {
if (req.url != '/') {
var file = req.url.substring(1);
var type = path.extname(file);
if (fs.existsSync(file)) {
if (type == '.js' || type == '.css') {
if (type == '.js') {
res.writeHead(200, { "Content-Type" : "application/javascript" });
} else if (type == '.css') {
res.writeHead(200, { "Content-Type" : "text/css" });
} else if (type == '.html') {
res.writeHead(200, { "Content-Type" : "text/html" });
}
statico.use(file, {}, function (data) {
res.end(data);
});
}
}
}
}
var statico = {
setup : function (req, res) {
setuper(req, res);
},
use : function (filename, replace, cb) {
if (typeof replace == 'undefined') {
var promise = new Promise(function (resolve, reject) {
var stream = fs.createReadStream(filename);
stream.on('data', function (chunk) {
var str = chunk.toString();
resolve(str);
});
});
} else {
var promise = new Promise(function (resolve, reject) {
var stream = fs.createReadStream(filename);
stream.on('data', function (chunk) {
var str = statico.replacer(chunk.toString(), replace);
if (typeof cb === 'undefined') {
resolve(str);
} else {
cb(str);
}
});
});
}
return promise;
},
replacer : function (string, replace) {
var re = /\$\{([^\}]+)?\}/g, match;
while(match = re.exec(string)) {
string = string.replace(match[0], replace[match[1]])
re.lastIndex = 0;
}
return string;
}
};
module.exports = statico;