-
Notifications
You must be signed in to change notification settings - Fork 73
/
fs2http.js
65 lines (57 loc) · 1.84 KB
/
fs2http.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
var Q = require("q");
var HTTP = require("./http");
var URL = require("url");
exports.Client = Client;
function Client(fs) {
var self = Object.create(Client.prototype);
self.request = function (request) {
return Q.when(request, function (request) {
request = HTTP.normalizeRequest(request);
var url = URL.parse(request.url);
if (url.protocol !== "file:") {
return {
status: 404,
headers: {},
body: ["Can't access protocol " + url.protocol]
};
} else {
var path = url.pathname;
return fs.open(path, {
charset: request.charset
}).then(function (body) {
return {
status: 200,
headers: {},
body: body
};
});
}
});
};
self.read = function (request, qualifier) {
qualifier = qualifier || function (response) {
return response.status === 200;
};
return Q.when(exports.request(request), function (response) {
if (!qualifier(response)){
var error = new Error("HTTP request failed with code " + response.status);
error.response = response;
throw error;
}
return Q.invoke(response.body, "read");
});
};
return self;
}
exports.request = function (request) {
return Q.fcall(require.async || require, "./fs")
.then(function (fs) {
return Client(fs).request(request);
});
};
exports.read = function (request, qualifier) {
return Q.fcall(require.async || require, "./fs")
.then(function (fs) {
return Client(fs).read(request);
});
};