forked from Laboratoria/SAP004-md-links
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
executable file
·56 lines (49 loc) · 1.29 KB
/
common.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
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const fetch = require('node-fetch');
function forEachFile(filePath, callback) {
const resolveFile = (file) => callback(path.resolve(file));
if (filePath.includes('.md')) {
if (fs.existsSync(filePath)) {
resolveFile(filePath);
} else {
throw new Error('Markdown file not found by path');
}
} else {
const files = glob.sync(`${filePath}**/*.md`);
files.forEach(resolveFile);
}
}
function findLinks(text, file) {
const regx = /(\[.*\])(\(.*\))/gim;
const links = text.match(regx) || [];
return links.map(link => {
const groups = /\[(.*)\]\((.*)\)/gim;
const [, text, href] = groups.exec(link);
return { href, text, file };
});
}
function extractLinksFromFile(filePath) {
const textMD = fs.readFileSync(filePath).toString('utf-8');
return findLinks(textMD, filePath);
}
function validateLink(link) {
return fetch(link.href)
.then(
(res) => ({
...link,
status: res.status,
})
)
.catch(
() => ({
...link,
status: 'DNS problem',
})
);
}
exports.extractLinksFromFile = extractLinksFromFile;
exports.forEachFile = forEachFile;
exports.validateLink = validateLink;
exports.findLinks = findLinks;