forked from apachecn/doctool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extcode.js
82 lines (63 loc) · 1.77 KB
/
extcode.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
var fs = require('fs')
var path = require('path')
var isFile = f => fs.statSync(f).isFile()
function recoverFile(fname) {
if(!fname.endsWith('.md'))
return
if(!fs.existsSync(fname + '.json')) {
console.log(fname + ' 未提取')
return
}
console.log(fname)
var pres = JSON.parse(fs.readFileSync(fname + '.json', 'utf-8'))
var co = fs.readFileSync(fname, 'utf-8')
for(var [i, p] of pres.entries())
co = co.replace(`[PRE${i}]`, p)
fs.writeFileSync(fname, co)
fs.unlinkSync(fname + '.json')
}
function extractFile(fname) {
if(!fname.endsWith('.md'))
return
if(fs.existsSync(fname + '.json')) {
console.log(fname + ' 已提取')
return
}
console.log(fname)
var co = fs.readFileSync(fname, 'utf-8')
var pres = []
co = co.replace(/```\w*$[\s\S]+?^\x20*```/mg, s => {
pres.push(s)
var idx = pres.length - 1
return `[PRE${idx}]`
})
fs.writeFileSync(fname + '.json', JSON.stringify(pres))
fs.writeFileSync(fname, co)
}
function processDir(dir, op) {
var files = fs.readdirSync(dir)
for(var f of files) op(path.join(dir, f))
}
var recoverDir = dir => processDir(dir, recoverFile)
var extractDir = dir => processDir(dir, extractFile)
function extract(fname) {
if(isFile(fname))
extractFile(fname)
else
extractDir(fname)
}
function recover(fname) {
if(isFile(fname))
recoverFile(fname)
else
recoverDir(fname)
}
function main() {
var op = process.argv[2]
var fname = process.argv[3]
if(['e', 'extract'].includes(op))
extract(fname)
else if(['r', 'recover'].includes(op))
recover(fname)
}
if(require.main === module) main()