forked from Laboratoria/SCL013-md-links
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
75 lines (75 loc) · 2.07 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
const fs = require("fs");//Nos permite acceder al sistema de archivos, viene incorporado en node
let file = process.argv[2];//Toma lo que se le da desde consola
//const axios = require ('axios');//librería para hacer solicitudes HTTP
const fetch1 = require("node-fetch");
const chalk = require('chalk');
const fetch = require("fetch");
const fetchUrl = fetch.fetchUrl;
//Función que lee el archivo
const getMd = (file) => {
return new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (err, file) => {
if (err) {
return reject(err)
} else {
resolve(file)
}
})
})
}
//stats
const urlStats = (links) => {
let ok = 0;
let broken = 0;
for (let i = 0; i < links.length; i++) {
fetch1(links[i])
.then((response) => {
if (response.status === 200) ok++;
return response;
})
.then((response) => {
if (response.status !== 200) broken++;
return response;
})
.then(() => {
if (ok + broken === links.length)
console.log(`
${chalk.blue("✔ Total : " + links.length)}
${chalk.green("✔ Unique :" + ok)}
${chalk.red("✖ Broken :" + broken)}`
);
});
}
};
//Función que lee los links de la ruta espeficificada
const expReg = /https?:\/\/(?!.*:\/\/)\S+(?=\))/g;
fs.readFile(file, "utf-8", (err, file) => {
if (err) {
console.log(err);
} else {
let links = file.match(expReg);
console.log(file.match(expReg));
links.forEach(element => {
getStatus(element)
.then(res => {
console.log(chalk.cyanBright("El link"), chalk.cyanBright(element), chalk.cyanBright("es"), chalk.yellowBright(res));
})
.catch(err => {
console.log(err);
})
})
urlStats(links);
//console.log("Esto es lo que tiene el .md seleccionado", file);
}
});
const getStatus = (url) => {
return new Promise((resolve, reject) => {
fetchUrl(url, (error, meta) => {
if (error) {
reject(error)
} else {
resolve([meta.status]);
}
})
});
};