forked from Laboratoria/SAP010-md-links
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (84 loc) · 2.62 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
81
82
83
84
85
86
87
88
89
90
91
92
93
const fs = require('fs');
const pathModule = require('path');
const axios = require('axios');
function mdLinks(path) {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err) {
reject(new Error(`Erro ao verificar o caminho: ${err.message}`));
} else if (stats.isFile() && path.endsWith('.md')) {
const regex = /\[([^[\]]+)\]\(([^()\s]+|\S+)?\)/g;
fs.readFile(path, 'utf8', (readErr, fileContent) => {
if (!readErr) {
const strFiles = fileContent.toString();
const links = [];
const matches = [...strFiles.matchAll(regex)];
matches.forEach((match) => {
const [, text, href] = match;
const link = {
href,
text: text.replace(/[\r\n]+/g, '').trim(),
file: path,
};
links.push(link);
});
resolve(links);
}
});
} else if (stats.isDirectory()) {
try {
const fileList = fs.readdirSync(path);
const filteredList = fileList.filter(
(file) => pathModule.extname(file) === '.md',
);
const promises = filteredList.map((file) => mdLinks(pathModule.join(path, file)));
Promise.all(promises)
.then((results) => {
const linksArray = results.reduce(
(accumulator, links) => accumulator.concat(links),
[],
);
resolve(linksArray);
});
} catch (error) {
reject(
new Error(`Erro ao ler o diretório: ${path}: ${error.message}`),
);
}
}
});
});
}
// retorna os links de um arquivo específico (como objetos)
function getHTTPStatus(linksObject) {
let brokenCount = 0;
const linkPromises = linksObject.map((links) => axios
.get(links.href)
.then((response) => {
const updatedLinks = { ...links, status: response.status };
if (response.status >= 200 && response.status < 300) {
updatedLinks.ok = 'Ok';
} else if (response.status >= 300) {
updatedLinks.ok = 'FAIL';
brokenCount += 1;
}
return updatedLinks;
})
.catch(() => {
const updatedLinks = { ...links };
updatedLinks.status = 'Erro ao realizar requisição HTTP';
updatedLinks.ok = 'FAIL';
brokenCount += 1;
return updatedLinks;
}));
return Promise.all(linkPromises).then((updLinks) => ({
linksObject: updLinks,
brokenCount,
}));
}
module.exports = {
mdLinks,
getHTTPStatus,
};
// teste computador novo
// teste 2