-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtomd.js
145 lines (121 loc) · 2.76 KB
/
tomd.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
var toMD = require('to-markdown');
var fs = require('fs');
var path = require('path')
var isDir = s => fs.statSync(s).isDirectory()
function main() {
var fname = process.argv[2]
if(!fname) {
console.log('请指定文件或目录。')
process.exit();
}
if(isDir(fname))
processDir(fname)
else
processFile(fname)
}
function processDir(dir) {
var files = fs.readdirSync(dir)
for(var fname of files) {
fname = path.join(dir, fname)
processFile(fname)
}
}
function tomd(html) {
return toMD(html, {
gfm: true,
converters: myConventors,
});
}
function processFile(fname) {
if(!fname.endsWith('.html'))
return;
console.log(`file: ${fname}`)
var co = fs.readFileSync(fname, 'utf-8')
.replace(/<a[^>]*\/>/g, '');
var mdName = fname.replace(/\.html/g, '.md')
var md = tomd(co)
fs.writeFileSync(mdName, md);
}
// my conventors for https://github.com/domchristie/to-markdown
function cell(content, node) {
var index = Array.prototype.indexOf.call(node.parentNode.childNodes, node);
var prefix = ' ';
if (index === 0) { prefix = '| '; }
return prefix + content + ' |';
}
var myConventors = [
//<p> in <td>
{
filter: function(n) {
return n.nodeName == 'P' &&
n.parentNode.nodeName === 'TD'
},
replacement: function(c){return c}
},
//<dl> (to <p>)
{
filter: ['dd', 'dt'],
replacement: function (c) {
return '\n\n' + c + '\n\n';
}
},
{
filter: 'dl',
replacement: function(c){return c}
},
// <em> & <i>
{
filter: ['em', 'i'],
replacement: function(c){return '*' + c + '*'}
},
//<span> & <div>
{
filter: ['span', 'div'],
replacement: function(c){return c}
},
//sth to clean
{
filter: ['style', 'base', 'meta', 'script'],
replacement: function(){return ''}
},
// <code>
{
filter: ['code', 'tt', 'var', 'kbd'],
replacement: function(c, n) {
if(n.parentNode.nodeName !== 'PRE')
return '`' + c + '`';
else
return c;
}
},
//non-link <a>
{
filter: function (n) {
return n.nodeName === 'A' && !n.getAttribute('href');
},
replacement: function(){return ''}
},
// <pre>
{
filter: 'pre',
replacement: function(c) {
return '\n\n```\n' + c + '\n```\n\n';
}
},
// tags in <pre>
{
filter: function(n) {
return n.parentNode.nodeName === 'PRE' &&
n.nodeName != 'BR'
},
replacement: function(c){return c}
},
//<th> & <td>
{
filter: ['th', 'td'],
replacement: function (c, n) {
return cell(c.replace(/\|/g, '|'), n);
}
},
];
if(module == require.main) main()