forked from Laboratoria/SAP004-md-links
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd-links.js
63 lines (53 loc) · 1.33 KB
/
md-links.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
const fs = require('fs');
const marked = require('marked');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const validateLink = require('./validate-link')
function readFile(path){
try {
const data = fs.readFileSync(path, 'ascii');
return data;
}
catch (err) {
throw new Error('Ocorreu um erro ao ler o arquivo');
}
}
function parseMdToHtml(markdown) {
return marked(markdown);
}
function getLinks (html, file) {
const dom = new JSDOM(html);
const links = dom.window.document.querySelectorAll('a');
const parsedLinks = parseLinks(links, file)
return parsedLinks;
}
function parseLinks(links, file) {
return Array.from(links).map((link) => {
return {
href:link.href,
text:link.textContent,
file,
}
})
}
function validateLinks(links){
const linkPromises = links.map(validateLink)
return Promise.all(linkPromises)
}
function mdlinks(path, options) {
return new Promise (function(resolve, reject) {
try {
const fileContent = readFile(path)
const htmlContent = parseMdToHtml(fileContent)
const links = getLinks(htmlContent, path)
if (options && options.validate){
validateLinks(links).then(result => resolve(result))
} else {
resolve(links);
}
} catch (error) {
reject(error)
}
})
}
module.exports = mdlinks;