-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (53 loc) · 2.11 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
const { promisify } = require('util');
const fs = require('fs');
const axios = require('axios');
/* eslint-disable max-len */
/**
* Checks file for broken links and images.
* @param {String} filePath path to the file that should be checked for broken links and images (for example: './path/to/file/README.md').
* @param {Array} ignoreLinks array of links that should not be checked (for example: ['https://www.linkedin.com/in/test/']).
* @returns {Array} array of broken links.
*/
async function checkFile (filePath, ignoreLinks = []) {
/* eslint-enable max-len */
const pathToFile = process.env.TARGET_FILE_PATH || filePath;
const readFile = promisify(fs.readFile);
const text = await readFile(pathToFile, 'utf8');
const statusCodeOk = 200;
let brokenLinks = [];
// Filter out only links that start with http(s) and end with ) or " or '
// Using negative lookahead ?! to filter out localhost:
const links = text.match(/https?:\/\/(?!.*(localhost:)).*?[\)|"|']/gi);
if (links) {
// Clear links from last character ) or " or '
let filteredLinks = links.map((value) => value.slice(0, -1));
// Remove the ignored links if any
if (ignoreLinks.length > 0) {
filteredLinks = filteredLinks.filter((value) => {
return !ignoreLinks.includes(value);
});
}
console.log(`Found ${filteredLinks.length} link(s):`);
console.log(filteredLinks);
const responses = await Promise.all(filteredLinks.map(async (value) => {
try {
const response = await axios.get(value);
return response.status;
} catch (error) {
console.error(`Found broken link (${error}): ${value}`);
}
}));
responses.map((value, index) => {
if (value !== statusCodeOk) { brokenLinks.push(filteredLinks[index]); }
});
} else {
console.log(`No links found in ${pathToFile}`);
}
return brokenLinks;
}
if (process.env.TARGET_FILE_PATH) {
checkFile(process.env.TARGET_FILE_PATH);
}
module.exports = {
checkFile
};