-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathproxy_writter.js
More file actions
50 lines (40 loc) · 1.45 KB
/
Copy pathproxy_writter.js
File metadata and controls
50 lines (40 loc) · 1.45 KB
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
var fs = require('fs')
, path = require('path')
, clrs = require('colors')
, mdp = require(path.join(__dirname, 'mkdirp.js'))
;
var proxyWritter = function(hostname, pathname) {
var self = this;
var stream = null;
this.host = hostname.replace(/[^a-zA-Z0-9\-\.]/g, "");
this.path = pathname.replace(/[^a-zA-Z0-9\-\.\_\/]/g, "_");
if(this.path.length > 256) this.path = this.path.slice(0,256);
var basepath = "/tmp/proxy/" + this.host;
this.filename = path.resolve( basepath + this.path);
// if path is beyond basepath, set relative request path
if(this.filename.indexOf(basepath) != 0) this.filename = basepath + "/relative_request_" + Date.now();
// if does not have extension, create directory and set file name to index.html
if(this.filename == basepath || path.basename(this.filename).indexOf(".") == -1) this.filename = this.filename + "/index.html";
this.write = function(d) {
if(stream) {
try {
stream.write(d)
} catch(err) {
console.log(("Ops, failed creating file: " + self.filename + ", reason: " + err).red);
stream = null;
}
} else {
console.log("Stream not open for file: " + self.filename.red);
}
}
this.end = function() {
if(stream) stream.end();
}
mdp.mkdirp(path.dirname(this.filename), 0755, function() {
if(fs.existsSync(self.filename)) {
self.filename += "-" + Date.now();
}
stream = fs.createWriteStream(self.filename, {flags:'w', 'encoding':null});
})
}
module.exports = proxyWritter