forked from andersontr15/req-to-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (52 loc) · 1.52 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
var request = require('request-promise');
var fs = require('fs');
var store = function(url, fileName, callback) {
if(!url || !fileName) {
throw new Error("Please provide a valid url & fileName");
}
var options = {
url: url,
headers: {
'User-Agent': 'request'
}
};
request(options)
.then(function(response) {
fs.writeFile(fileName, response, function(err) {
if(err) {
return callback(err, null);
};
var data = JSON.parse(response);
return callback(null, data);
});
})
.catch(function(error) {
return callback(error, null);
});
};
var getJSON = function(fileName) {
if(!fileName || typeof fileName !== 'string') {
throw new Error("Please provide a valid url");
}
return new Promise(function(resolve, reject) {
try {
fs.readFile(fileName, 'utf8', function(err, data) {
if(err) {
reject('File does not exist! Please create the file in your directory and try again!');
}
else {
resolve(JSON.parse(data));
};
});
}
catch(error) {
if(err.code === 'ENOENT') {
reject('File does not exist! Please create the file in your directory and try again!');
};
};
});
};
module.exports = {
store: store,
getJSON: getJSON
};