/
index.js
77 lines (67 loc) · 1.76 KB
/
index.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
'use strict';
var https = require('https');
/**
* Get an individual file and return a stream in the callback.
*
* ```js
* var get = require('get-file');
* get('jonschlinkert/get-file', 'package.json', function(err, res) {
* if (err) return console.error(err);
* var file = fs.createWriteStream('package.json');
* res.pipe(file);
* });
* ```
* @param {String} `repo` Repository to get file from.
* @param {String} `filename` file to get.
* @param {Function} `cb` Callback function that takes `err` and `res` arguments.
* @api public
*/
function get(repo, filename, cb) {
var filepath = 'https://raw.githubusercontent.com/' + repo + '/master/' + filename;
https.get(filepath, function(res) {
if (res.statusCode !== 200) {
cb(new Error('Cannot find ' + filename));
} else {
cb(null, res);
}
})
.on('error', cb);
}
/**
* List the files in a given repository.
*
* ```js
* var get = require('get-file');
* get.files('jonschlinkert/get-file', function(err, files) {
* if (err) return console.error(err);
* console.log(files);
* });
* ```
* @param {String} `repo` Repository to get list of files.
* @param {Function} `cb` Function that takes `err` and `files` arguments
* @api public
*/
get.files = function(repo, cb) {
var files = [];
https.get({
host: 'api.github.com',
path: '/repos/' + repo + '/contents',
headers: {'User-Agent': 'get-file node.js application'}
}, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var list = JSON.parse(body);
for (var i = 0; i < list.length; ++i) {
files.push(list[i]);
}
cb(null, files);
});
});
};
/**
* Expose `get`
*/
module.exports = get;