forked from Laboratoria/SCL009-md-links
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd-links.js
111 lines (81 loc) · 2.32 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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/env node
const fs = require('fs'); // leo los archivos
const marked = require('marked'); // extraigo los links y los meto en array
const fileHound = require('filehound'); // read directory
const path = require('path');
let links = [];
/*Si es un archivo o ruta, llama a la función correspondiente*/
const mdLinks = (path, options={}) => {
return new Promise ((resolve, reject) => {
if(!path || !options ){
throw(new Error("INGRESA UNA RUTA VÁLIDA!"))
}
fs.stat(path, (error, stats) => {
if (error) {
throw(new Error("Ingresa un archivo/ruta QUE EXISTA"))
}
if (stats.isFile()) {
readLinks(path)
.then(url=>{
resolve(url)
})
.catch(err=>{
reject(err)
})
} if (stats.isDirectory()) {
readRoute(path)
.then(res=>{
res.forEach(links=>{
resolve(readLinks(links))
})
})
.catch(err=>{
reject(err)
})
}
});
}); // fin promise
}
/*F(x) para leer links convertida en promesa */
const readLinks = (files) => {
return new Promise ((resolve, reject) => {
if(path.extname(files) != '.md'){
throw(new Error("Debes escoger un archivo con extensión MD"))
}
fs.readFile(files, "utf8", (err, data) => {
if (err){
reject(err)
}
//console.log("Solo los links de ese archivo", data);
links = [];
const renderer = new marked.Renderer();
renderer.link = (href, title, text, ruta) => {
links.push({
href: href,
text: text,
ruta: files
});
//console.log("links encontrados", links)
} //fin rendered
marked(data, { renderer: renderer })
resolve(links)
}) //fin readFiles
}) // fin promesa
} //Fin función readLinks
/*F(x) que lee directorios, posteriormente llama a readLinks*/
const readRoute = (route) => {
return new Promise((resolve, reject)=>{
fileHound.create() //sólo lee directorios
.discard('node_modules')
.paths(route)
.ext('md')
.find()
.then(res=>{
resolve(res)
})
.catch(err=>{
reject(err)
})
})
}
module.exports= mdLinks;