-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·80 lines (75 loc) · 2.13 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
78
79
80
#!/usr/bin/env node
var colors = require('colors');
var readline = require('readline');
var open = require('open');
var Promise = require('bluebird');
// Promises...Promises...
var request = Promise.promisify(require('request'));
var opt = '';
var check;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Read the command line arguments
process.argv.forEach(function(val, index, array) {
if (index >= 2) {
opt += val + ' ';
}
});
// Make sure that a key-word is passed
if(opt == '') {
console.log(colors.redBG('ERROR: NO KEY-WORD ENTERED!!'));
process.exit(0);
}
//make the API request
request('http://it-ebooks-api.info/v1/search/' + opt.trim()).spread(function(response, body) {
return JSON.parse(body);
}).then(function(s) {
if (s.Total == '0') {
// No books found!!
throw "OOPS!! NO ITEMhS FOUND";
}
var i = 0;
(s.Books).forEach(function(book) {
console.log(colors.red(i+1)+colors.red(". ")+colors.bold(book.Title));
if (book.SubTitle == null) {
console.log("** No description available **");
} else {
console.log(book.SubTitle);
}
i++;
console.log();
check = i;
});
return s;
}).then(function(data) {
rl.question(colors.cyanBG('Enter the option number of the book you want to download:') +'\n', function(result) {
// Check if option entered is valid or not
if (!(parseInt(result) > 0 && parseInt(result) <= (check+1) && parseInt(result) == parseFloat(result))) {
console.log('PLEASE ENTER A VALID OPTION!!!');
process.exit(1);
}
request('http://it-ebooks-api.info/v1/book/'+(data).Books[(result)-1].ID).spread(function (response, body) {
return (JSON.parse(body)).Download;
}).then(function(val) {
open(val);
}).catch(function(err) {
if ((err.message) == 'getaddrinfo ENOTFOUND') {
console.log(colors.redBG("ERROR: NO INTERNET CONNECTIVITY"));
process.exit(1);
} else {
console.log(err);
}
});
rl.close();
});
}).catch(function(err) {
if ((err.message) == 'getaddrinfo ENOTFOUND') {
console.log(colors.redBG("ERROR: NO INTERNET CONNECTIVITY"));
process.exit(1);
} else {
console.log(colors.blackBG(err));
process.exit(1);
}
});