-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileCacheWriter.js
More file actions
111 lines (76 loc) · 1.87 KB
/
fileCacheWriter.js
File metadata and controls
111 lines (76 loc) · 1.87 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
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
var path = require('path');
var fs = require('fs');
var exec = require('child_process').exec;
var cacheDir = "tmp";
function log (args) {
console.log("fileCacheWriter.js: " + args);
}
var write = function(item, response) {
log("writing " + item.url)
var reqParts = [cacheDir].concat(item.url.substr(1).split("/"));
var reqFile = reqParts.pop() || "index.html";
var reqDir = reqParts.join("/") + "/";
var url = reqDir + reqFile;
var bodyFile = fs.createWriteStream(url) ;
bodyFile.on("close", function () {
var headerFile = fs.createWriteStream(url + ".header"); // util function?
headerFile.write(JSON.stringify({"statusCode": response.statusCode, "headers": response.headers }))
headerFile.end()
});
response.pipe(bodyFile);
}
var rm = function (url, cb) {
if (url.indexOf(cacheDir) != 0 ) {
return
}
var callback = function(err) {
if (typeof cb === 'function') {
cb(err);
}
};
fs.stat(url, function(statErr, stats) {
if (statErr) {
return
}
if (stats.isFile()) {
console.log("doing unlink")
fs.unlink(url, callback);
}
if (stats.isDirectory()) {
console.log("doing rm -r")
exec("rm -r " + url, callback)
}
})
}
var prepare_paths = function(url, cb) {
var parts = [cacheDir].concat(url.substr(1).split("/"));
parts.pop();
console.log("preparing path: " + parts.join("/"))
var test = [];
var mkdirs = function(next_item) {
if (!next_item) {
if (cb) cb()
return
}
test.push(next_item)
path.exists(test.join("/"), function(exists) {
if (!exists) {
fs.mkdir(test.join("/"), 0755, function(err) {
if (err) {
log(err)
if (cb) cb()
return
} else {
mkdirs(parts.shift()) ;
}
})
} else {
mkdirs(parts.shift())
}
})
}
mkdirs(parts.shift(), cb)
}
exports.write = write;
exports.rm = rm;
exports.prepare_paths = prepare_paths;