aboutsummaryrefslogtreecommitdiff
path: root/test/fetch.js
blob: eccdd71f6dbd26b3d4440714a002d76d8377da71 (about) (plain)
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
var fs = require("fs");
var parse = require("url").parse;
var path = require("path");

try {
    fs.mkdirSync("./tmp");
} catch (e) {
    if (e.code != "EEXIST") throw e;
}

function local(url) {
    return path.join("./tmp", encodeURIComponent(url));
}

function read(url) {
    return fs.createReadStream(local(url));
}

module.exports = function(url, callback) {
    var result = read(url);
    result.on("error", function(e) {
        if (e.code != "ENOENT") return callback(e);
        var options = parse(url);
        options.rejectUnauthorized = false;
        require(options.protocol.slice(0, -1)).get(options, function(res) {
            if (res.statusCode !== 200) return callback(res);
            res.pipe(fs.createWriteStream(local(url)).on("close", function() {
                callback(null, read(url));
            }));
        });
    }).on("open", function() {
        callback(null, result);
    });
};