-
Notifications
You must be signed in to change notification settings - Fork 4
/
file.js
97 lines (85 loc) · 2.23 KB
/
file.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
'use strict';
var fs = require('fs');
var path = require('path');
var url = require('url');
var events = require('events');
var util = require('util');
var request = require('urllib').request;
module.exports = File;
function File(urlPath, options) {
urlPath = url.parse(urlPath).pathname;
this.options = options;
this.urlPath = urlPath;
this.localPath = path.join(options.directory, urlPath);
this.remotePath = url.resolve(options.proxy, urlPath);
}
util.inherits(File, events.EventEmitter);
File.prototype.end = function(cb) {
var that = this;
this.getLocal(function(err, data) {
if (!err) {
// find file from directory
that.emit('found', that.localPath);
cb(null, data);
} else {
that.emit('not found', that.localPath);
if (that.options.beforeProxy) {
that.emit('before proxy', that.localPath);
that.options.beforeProxy.call(that, that.urlPath, cb, requestProxy);
} else {
requestProxy();
}
}
function requestProxy() {
if (that.options.proxy) {
// find file from remote server
that.getRemote(cb);
} else {
// not found
cb(err);
}
}
});
return this;
};
File.prototype.getLocal = function(cb) {
fs.readFile(this.localPath, cb);
return this;
};
File.prototype.getRemote = function(cb) {
var that = this;
var opt = {
gzip: true,
followRedirect: false,
rejectUnauthorized: false
};
request(this.remotePath, opt, function(err, data, res) {
if (err) {
that.emit('not found', that.remotePath);
return cb(err);
}
if (res.statusCode >= 300) {
that.emit('not found', that.remotePath);
return cb(new Error(res.statusCode));
}
that.emit('found', that.remotePath);
if (that.options.cache) {
mkdirp(that.localPath);
fs.writeFile(that.localPath, data, function(err) {
!err && that.emit('cached', that.localPath);
cb(err, data);
});
} else {
cb(null, data);
}
});
return this;
};
function mkdirp(filePath) {
var dirname = path.dirname(filePath);
var dirs = dirname.split('/');
for (var i = 2; i <= dirs.length; i++) {
var p = dirs.slice(0, i).join('/');
!fs.existsSync(p) && fs.mkdirSync(p);
}
}