-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
55 lines (46 loc) · 1.83 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
const request = require('request');
const TurndownService = require('turndown');
const util = require('util');
const fs = require('fs');
const cheerio = require('cheerio');
const rules = require('./rules');
const asyncGetRequest = util.promisify(request.get).bind(request);
const asyncWriteFile = util.promisify(fs.writeFile).bind(fs);
const turndownService = new TurndownService();
async function convert(url) {
try {
const resp = await asyncGetRequest(url);
if (resp.statusCode !== 200) {
console.log('Error while fetching URL');
return resp.statusMessage;
}
turndownService.addRule('lineBreakRule', rules.linebreakRule);
turndownService.addRule('figureDivNoLineBreakRule', rules.figureDivNoLinkeBreakRule);
turndownService.addRule('figureCapNoLineBreakRule', rules.figCaptionEnclosing);
turndownService.addRule('codeFormattingRule', rules.codeFormattingRule);
turndownService.keep(['b']);
const $ = cheerio.load(resp.body);
const html = $('.postArticle-content').html();
const markdown = turndownService.turndown(html);
const time = $('time').attr('datetime').split('T')[0];
const heading = $('h1', '.section-inner.sectionLayout--insetColumn')
.html();
return Promise.resolve({ markdown, heading, time });
} catch (err) {
return Promise.reject(err);
}
}
async function generateFile(data, paddingBefore = '', paddingAfter = '') {
try {
const fileName = `${data.time}-${data.heading}.md`;
const toWrite = paddingBefore + data.markdown + paddingAfter;
await asyncWriteFile(fileName, toWrite);
console.log(`Success - Written file ${fileName}`);
} catch (err) {
console.log(err);
}
}
module.exports = {
convert,
generateFile,
};