forked from Laboratoria/CDMX009-MdLinks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
90 lines (80 loc) · 2.54 KB
/
app.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
81
82
83
84
85
86
87
88
89
90
const path = require('path');
const fs = require('fs');
const fetch = require('node-fetch');
const colors = require('colors/safe');
//make sure its a markdown file
const isMarkDown = uri => path.extname(uri) === '.md' ? true : false;
//The app must read a file
const readFile = () => {
let index = process.argv.indexOf("--file"); //flag--> --file
if (index < 0) return console.log("no se encuentra el archivo");
let uri = process.argv[index + 1];
if (isMarkDown(uri)) {
let fileInformation = fs.readFileSync(uri, 'utf8');
showLinks(fileInformation);
}
}
//finding links
const showLinks = (fileInformation) => {
console.log("all the information contained in the md file", fileInformation);
let regEx = /\bhttps:\/\/([a-z0-9.a-z0-9\/]+)([-a-z0-9?=_&#\/]+)([.a-z0-9]+)/gi;
let result = fileInformation.match(regEx);
checkLinkStatus(result);
}
//check link status
const checkLinkStatus = (allLinks) => {
let promises = allLinks.map(link => fetch(link)
.then(res => {
let thrownAnswer = {
url: res.url,
status: res.status,
text: res.statusText
}
if (thrownAnswer.status === 200) {
console.log(colors.blue(res.status), colors.grey(res.statusText), ('url:', link))
} else {
console.log(colors.yellow(res.status), colors.green(res.statusText), ('url:', link))
}
return thrownAnswer
})
.catch(error => {
let bug = {
url: link,
status: 'error',
text: error.errno
}
if (bug.status === 'error') {
console.log(colors.yellow(bug.status), colors.red(bug.text), ('url:', link))
}
return bug
})
)
return Promise.all(promises)
.then(res => {
arrayCount(res)
})
}
//Obtaining statistics
function arrayCount(res) {
console.log(colors.underline('The total Links: '), (res.length))
console.log(colors.magenta('Broken Links: ', res.reduce((accountant, element) => {
if (element.status !== 200) {
return accountant += 1
}
return accountant
}, 0)))
console.log(colors.green('Works links: ', res.reduce((accountant, element) => {
if (element.status === 200) {
return accountant += 1
}
return accountant
}, 0)))
return res
}
module.exports = {
readFile,
showLinks,
isMarkDown,
checkLinkStatus,
arrayCount
}